java 未知深度的嵌套哈希图
我有一个要求,我需要有一个嵌套的哈希图。但深度将在运行时决定。 例如,如果在运行时,用户说 3, 那么我的 hashmap 应该是这样的,
HashMap<String, HashMAp<String, HashMap<String, String>>>
如果他说 4 那么
HashMap<String, HashMAp<String, HashMap<String, HashMap<String, String>>>>
有什么方法可以实现这种功能吗?其他一些 API 或工具包?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
哦,这几乎肯定是一个非常糟糕的主意。
听起来您确实想要一棵树或图,但不知道如何编写它,因此您发明了这种表示法来尝试使其与 HashMap 一起使用。
不。
弄清楚如何正确地编写你需要的内容,你会变得更好。
没有图书馆可以做你想做的事情,这是有充分理由的——你不应该这样做。
Oh, this is almost certainly a very bad idea.
You sound like you really want a tree or graph and don't know how to write it, so you're inventing this notation to try and make it work with HashMap.
Don't.
You'll be better off by figuring out how to write what you need properly.
There's no library to do what you want for a very good reason - you shouldn't.
您所要求的内容是在 Clojure 的 standardrad 库中实现的:与所陈述的相反,嵌套哈希图是表示树的明显且绝对合理的方式。
````clojure
(定义我的树
{:a {:aa 0}
:b 0
:c {:cc 0
:dd {:e 0})
(= (进入我的树 [:c :dd :e])
0)
你也可以通过对象图来表示它
,但是你会失去哈希图的通用性:对象无论如何都是概念性的哈希图,对其可以拥有的属性有限制。
What you ask is implemented in the standrad library of Clojure : contrary to what has been stated, nested hashmaps is the obvious and absolutely sane way to represent trees.
```clojure
(def my-tree
{:a {:aa 0}
:b 0
:c {:cc 0
:dd {:e 0})
(= (get-in my-tree [:c :dd :e])
0)
```
You can also represent it via un objet graph, but you'll lose the generality of hashmaps : objects are anyway conceptual hashmaps with restrictions on the attributes it can have.
您当然可以定义类型为
HashMap
的哈希映射,并以类型安全为代价获得动态深度。但达菲莫是正确的——你可能误用了这个结构。为什么你想要这样的类型?
您可能想查看这篇关于树的文章。您可能会发现它很有帮助。
You can certainly define a hash map with type
HashMap<String, ?>
and get dynamic depth at the cost of type safety.But duffymo is correct -- you are probably misusing the structure. Why do you want such a type?
You might want to look at this article on trees. You may find it helpful.