4

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??

Scott M.
  • 7,313
  • 30
  • 39
maverickprac
  • 543
  • 1
  • 5
  • 8
  • 5
    This is called a **Tree**. There is no general purpose interface for this in the API, but [I proposed one in another answer](http://stackoverflow.com/questions/4978487/why-java-collection-framework-doesnt-contain-tree-and-graph/4979522#4979522). (There is also a list of tree-like interfaces (and implementations) in this answer, maybe one of them fits your purpose. – Paŭlo Ebermann Mar 16 '11 at 00:02

3 Answers3

2

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.

duffymo
  • 305,152
  • 44
  • 369
  • 561
1
  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.

Foufou
  • 19
  • 2
0

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.

Kathy Van Stone
  • 25,531
  • 3
  • 32
  • 40