Map of cards and generics

I want to create a (recursive) map of maps. That is, the value of the Card type is another Card of the same type as the external card.

For instance:

Map<String, Map<String, Map<String, ... >>>> foo; 

Obviously, I need to somehow refer to the "definable type" or something like that. I think I could do:

 Map<String, Map<String, ?>> 

... and then just @SupressWarnings ("unchecked") passed by the inevitable warnings itself, but is there a better way?

+6
source share
2 answers

Create a helper class or interface to refer to the "defined type". Like this:

 class MyMap extends HashMap<String, MyMap> { ... } 

or

 interface MyMap extends Map<String, MyMap> { } 

(I don’t think you can do without such a helper class / interface. When "recursing" you need a name for the link.)

+6
source

In the end, what I did was similar to the aioobe solution, but avoids directly extending any particular map class:

 class StringTrie { private final Map<String, StringTrie> map = ...; ... } 

The disadvantage of hiding the map is, of course, that the class must manually expose any methods that are of interest to you and transfer them to the map. In my case, I only needed a couple, so it worked out well.

0
source

Source: https://habr.com/ru/post/897074/


All Articles