Tuesday 18 October 2016

java.util.TreeMap

java.util.TreeMap class

java.util.TreeMap class
  • We can store group of objects in the form of key-value pairs in Hashtable object.
  • Both key and values are objects only.
  • Keys can be unique and values can be duplicate.
  • Here group of objects means, it can allow us to store same type of objects only.
    • Same type means, assuming that all objects are in the form of integer types.
    • If trying to insert different type of objects then we ll get run time exception as ClassCastException
  • Size will increase dynamically.
  • Order is guarantee for ascending order.
--------------------------------------------------------------------------------------------
Program         :       Example on TreeMap class
Program name  :       TMDemo1.java
Output            :         
      {1=Nireekshan, 2=Sravan, 3=Hari, 9=Mohan, 10=Mouli}
     
import java.util.TreeMap;

class TMDemo1
{
       public static void main(String args[])
       {
             TreeMap treeMap = new TreeMap();
              
             treeMap.put(1, "Nireekshan");
             treeMap.put(2, "Sravan");
             treeMap.put(10, "Mouli");
             treeMap.put(9, "Mohan");
             treeMap.put(3, "Hari");
             
             System.out.println(treeMap);
       }
}

Compile       :         javac TMDemo1.java
Run             :         java TMDemo1
Output        :         
     {1=Nireekshan, 2=Sravan, 3=Hari, 9=Mohan, 10=Mouli}
--------------------------------------------------------------------------------------------
Thanks for your time.
Nireekshan