开发者

Map of maps and generics

I want to create a (recursive) map of maps. That开发者_C百科 is, the value of type of the Map is another Map of the same type as the outer map.

For example:

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

Evidently, I need some way to refer to "the type being defined" or something in order to do this. I guess I could do:

Map<String, Map<String, ?>>

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


Create an auxiliary class or interface to refer to "the type being defined". Like this:

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

or

interface MyMap extends Map<String, MyMap> {

}

(I don't think you can do without such auxiliary class / interface. When "recursing" you need a name to refer to.)


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

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

 ...
}

The downside of hiding the map being of course that the class needs to manually expose any methods which are interesting and pass them through to the map. In my case I only needed a couple so this worked well.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜