Dax Durax Dax Durax - 3 months ago 10
Java Question

Understanding TreeMaps

this is a noobie question regarding tree maps. I have read through the Java API and other documentation but am still unclear about just how this works.

From my understanding, a Tree in java (or any language) is sort of like a family tree; where you have say:

Layer 1 OldestGuy
Layer 2 OldGuy1 Oldguy2 OldGuy3 OldGuy4 OldGuy5
Layer 3 Guy1 Guy2 Guy3 Guy4 Guy5 Guy6........ etc


Where Layer 1 has 1 value (i.e. a central node) and from there there can be arbitrary amounts of values (or Guys) in each subsequent layer, and some of the "branches" can be longer than others (for example it could go OldestGuy -> OldGuy1 -> Guy1 & Guy2...Guyn whilst at the same time another branch is just OldestGuy -> OldGuy4)

With this ind mind I am trying to add values to a TreeMap in specific locations of specific branches whilst making specific connections but all I seem to be getting is the same results as a HashMap.

(it seems what I want to do requires something more than the TreeMap ....as the Key (or Layer(?) would be the same for several different values)

Any suggestions / explanations would be fantastic because I feel as if I am seriously barking up the wrong tree with this one.

I have seen examples of this being done using googles .jar, (such as a family tree) but I am just trying to understand this as there seems to be lots of conflict between TreeMap and Trees and how you can store data in them.

Answer

TreeMap is just an implementation of Map that happens to use a red-black tree behind the scenes. The details of the tree aren't exposed to you, so you can't store elements in arbitrary locations.

To put it another way, a TreeMap is not a general-purpose tree data structure. If that's what you actually want, perhaps take a look at this Stack Overflow question: Java tree data-structure?.

Comments