Wednesday, July 15, 2015

Java Collection Framework - Internal walk through -2

TreeMap
TreeMap is store key value pairs like HashMap. But it is sorted by key (ascending order) or by Comparator provided at the map creation time and it design to work as a red-black tree.
Red-black tree
   Red-black tree is a binary search tree with fallowing rules
·        Every node either red or black
·        Every null nodes consider as a black node
·        If node is red both child nodes are black
·        Every path from node to leaf contains the same number of black nodes                        

        

  Eg-:  (12,4,5,8,12,45,0,25,7,89,100,-7,2,20, 25.5)
Check with your own data set


In the TreeMap key objects should implement java.lang.comparable interface then override compareTo method for implied the “Natural Ordering”. TreeMap decides wether the key is smaller than or greater than to others. If comparable is not implemented, need to supply an implementation of java.util.comparator that would do comparing outside the key class itself .TreeMap internally maintains Lists of Entry class nodes which actually implemented the java.util.map.entry interface.


Set
Is unique collection of objects .There have three implementation of the Set, called HashSet, TreeSet and LinkedHashSet

HashSet
Its unordered set. Internally it use HashMap.Inside of HashSet class have class variable call ‘map’ which is an instance of the HashMap .when we adding values to the HashSet using add(element) internally it add values to ‘map’ by calling put(key,value) .use that element passing through the add method as a key and use dummy object as value for all elements

Object value=new Object();

HashMap internally check the uniqueness of the Key objects using equal method

TreeSet
TreeSet is sorted and internally using TreeMap.(functioning same like HashSet )   

LinkedHashSet
LinkedHashSet is ordered set which extends the HashSet.It uses Doubly Linked List for hold the order.



No comments:

Post a Comment