简体   繁体   English

深度未知的Java的嵌套hashmap

[英]nested hashmaps of unknown depth java

I have a requirement in which I need to have an nested hashmap. 我有一个需要嵌套的哈希图的要求。 But the depth would be decided at run time. 但是深度将在运行时确定。 Eg If at runtime, user says 3, then my hashmap should be like 例如,如果在运行时用户说3,那么我的哈希图应该像

HashMap<String, HashMAp<String, HashMap<String, String>>>

if he says 4 then 如果他说4

HashMap<String, HashMAp<String, HashMap<String, HashMap<String, String>>>>

Is there any way to implement this kind of functionality? 有什么方法可以实现这种功能? Some other API or toolkit?? 其他一些API或工具包?

  1. It is better to have 100 functions operate on one data structure than 10 functions on 10 data structures. 在一个数据结构上运行100个功能比在10个数据结构上运行10个功能更好。 Alan Perlis. 艾伦·佩利斯(Alan Perlis)。

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的standrad库中实现的:与已陈述的相反,嵌套的哈希图是表示树的明显且绝对明智的方法。 ```clojure (def my-tree {:a {:aa 0} :b 0 :c {:cc 0 :dd {:e 0}) ```clojure(def my-tree {:a {:aa 0}:b 0:c {:cc 0:dd {:e 0})

(= (get-in my-tree [:c :dd :e]) 0) ``` (=(获取我的树[: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. 您也可以通过非对象图来表示它,但是您将失去哈希图的一般性:对象始终是概念性哈希图,对其可具有的属性有所限制。

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. 您听起来好像真的想要一棵树或一个图形,却不知道如何编写它,所以您发明了这种表示法以尝试使其与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. 出于充分的理由,没有图书馆可以做您想做的事情-您不应该这样做。

You can certainly define a hash map with type HashMap<String, ?> and get dynamic depth at the cost of type safety. 您当然可以使用HashMap<String, ?>类型定义哈希映射,并以类型安全为代价获取动态深度。

But duffymo is correct -- you are probably misusing the structure. 但是duffymo是正确的-您可能滥用了该结构。 Why do you want such a type? 为什么要这样的类型?

You might want to look at this article on trees . 您可能想看一下有关树木的文章 You may find it helpful. 您可能会发现它很有帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM