Tuesday, February 26, 2013

TreeMap in Java 6 and java 7


TreeMap Class in Java

          In this post I am going to explain about some interesting difference between TreeMap class in Java 6 and Java 7 Collections. Before we are moving to TreeMap class we should know about the Map interface in Java Collection.

Map :
  1. If we want to represent a group of objects as key-value pairs then we should go for Map in.
  2. Both keys and values are objects in Map.
  3. Duplicate keys are not allowed but values can be duplicated.
  4. There is no relationship between Collection (for group of individual objects) and Map (for group of key-value pairs).
  5. Each key-value pair is called as Entry.


  
   6. There are two main Classes which is used often in our java program
       i) HashMap   ii) TreeMap

Here I am going to explain about TreeMap Class.

TreeMap:
  1. A class which implements the Sorted Map Interface.
  2. TreeMap implements the RED-BLACK Tree data structure concepts
  3. Insertion order is not preserved, because the all the entries are inserted based on some sorting order of keys.
  4. If we are depending on default natural ordering then the keys should be Homogeneous and Comparable. Otherwise we will get the ClassCastException.  Example :
              Case 1: (If Key doesn’t implement the comparable Interface)

              Output :

              Case 2: (If Map keys are not Homogeneous )

               Output :

  5.       If we are defining our own Sorting order using Comparator then the keys need not to be as
         homogeneous and comparable.
  6.       There are no restrictions on values they can be Heterogeneous and non -comparable.
  7.       Duplicate keys are not allowed but duplicate values are allowed. 

Comparison of TreeMap in Java 6 and Java 7 (based on Null acceptance)
Java 6
  1.       Insert an Entry with null key in empty TreeMap is allowed. But after inserting this entry if we 
         are trying to insert any other Entry we will get NullPointerException.(i.e TreeMap allows Null 
         key only once if it is an empty TreeMap)

  2.       Insert an Entry with null key in non-empty TreeMap we will get NullPointerException.

  3.       In TreeMap there are no restrictions on NULL values. We can use NULL values any no of 
         times in Map.

              Example :
            Output :

Java 7 

         1.      Here TreeMap shouldn’t allow NULL keys at any situation. If we are trying to insert the NULL keys we will get NullPointerException.

               Example :

              Output :
    
             

Reason : 

·                    In Java 7 The TreeMap class put method having the following line
   
 - compare(key, key); // type (and possibly null) check
       
      The above line is used to check the NULL and Type of Keys, But this line is not available in 
      Java 6 TreeMap Class.

No comments:

Post a Comment