nested hashmaps of unknown depth java

夙愿已清 提交于 2019-12-07 20:01:57

问题


I have a requirement in which I need to have an nested hashmap. But the depth would be decided at run time. E.g. If at runtime, user says 3, then my hashmap should be like

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

if he says 4 then

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

Is there any way to implement this kind of functionality? Some other API or toolkit??


回答1:


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.




回答2:


  1. It is better to have 100 functions operate on one data structure than 10 functions on 10 data structures. 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 (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.




回答3:


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.



来源:https://stackoverflow.com/questions/5319416/nested-hashmaps-of-unknown-depth-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!