Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding TreeMaps

Tags:

java

map

treemap

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.

like image 491
Dax Durax Avatar asked Mar 03 '12 21:03

Dax Durax


2 Answers

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

like image 121
Oliver Charlesworth Avatar answered Nov 15 '22 11:11

Oliver Charlesworth


public class TreeMap<K,V>
extends AbstractMap<K,V>
implements NavigableMap<K,V>, Cloneable, Serializable
  • Tree Map does not use hashing for storing keys. It's use Red-Black tree(self-balancing binary search tree.).
  • The TreeMap is sorted according to the natural ordering of its keys. Tree Map will always have all elements sorted.
  • Working of Tree Map is based on tree data structure.
  • Tree Map is not Synchronized and hence not thread safe.
  • Tree Map in java doesn't allow null key,but allow multiple null values.

Working of Tree Map is based on tree data structure.

  • Each node have 3 reference : PARENT,LEFT and RIGHT.
  • LEFT elements always less than parent element.
  • RIGHT elements always grater or equals of parent element.
like image 44
pradip jinjala Avatar answered Nov 15 '22 13:11

pradip jinjala