开发者

nested hashmaps of unknown depth java

开发者 https://www.devze.com 2023-02-17 05:30 出处:网络
I have a requirement in which I need to have an nested hashmap. But the depth would be decided at run time.

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 开发者_C百科kind of functionality? Some other API or toolkit??


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.


  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.


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.

0

精彩评论

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