地图和仿制药的地图

发布于 2024-12-04 00:51:09 字数 351 浏览 2 评论 0原文

我想创建一个(递归)地图。即该Map的type的值为与外层Map相同类型的另一个Map。

例如:

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

显然,我需要某种方式来引用“正在定义的类型”或其他东西才能做到这一点。我想我可以这样做:

Map<String, Map<String, ?>>

......然后我自己就通过了不可避免的警告@SupressWarnings(“unchecked”),但是有更好的方法吗?

I want to create a (recursive) map of maps. That 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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

橘和柠 2024-12-11 00:51:09

创建辅助类或接口来引用“正在定义的类型”。像这样:

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

或者

interface MyMap extends Map<String, MyMap> {

}

(我认为没有这样的辅助类/接口就不行。当“递归”时,你需要一个名字来引用。)

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.)

黯淡〆 2024-12-11 00:51:09

最后,我所做的与 aioobe 的解决方案类似,但避免直接扩展任何具体的地图类:

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

 ...
}

隐藏地图的缺点当然是该类需要手动公开任何有趣的方法并将它们传递给地图。就我而言,我只需要几个,所以效果很好。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文