TreeMap

TreeMap:

Tree map is used to store objects in the form of key-value pairs.

The dataStructure of TreeMap is Red-Black tree.

Treemap Implements navigablemap,and serializable and cloneable.

Treemap dosenot allow Insertion order.all objects are inserted according to some ordering of keys.

If We are depending on default natural sorting order Then Keys should be Homogeneous and comparable.otherwise we will get classcastException.

If we are depend on our customized sorting order then we need to go for comparator interface.

If we are using comparator then objects need not to be Homogeneous.

Treemap doenot allows Duplicate keys but It allows duplicate values.

It cannot allow null keys but it will accept null values.

Constructors:

TreeMap t = new TreeMap();

The above constructor is used for Default natural sorting order .

TreeMap t = new TreeMap(Comparator);

Example fo default natural sorting order:


package com.javalschool;

import java.util.TreeMap;

public class TreeMapDemo1 {

/**
* @param args
*/
public static void main(String[] args) {
TreeMap t = new TreeMap();
t.put(1, "AAA");
t.put(2, "BBB");
t.put(4, "ddd");
t.put(5,null);
System.out.println(t);


}

}


outPut:


{1=AAA, 2=BBB, 4=ddd, 5=null}

Example to Customized sorting order using comparator interface:


package com.javalschool;

import java.util.TreeMap;
public class MyComparator1 implements Comparator {

public int compare(Object o1 , Object o2) {
// TODO Auto-generated method stub
String s1 = (String)o1;
String s2 = (String)o2;
return s2.compareTo(s1);
}

}


public class TreeMapdemo2 {

/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
TreeMap t = new TreeMap(new MyComparator1());
t.put("AAA", 1);
t.put("BBB",2);
t.put("ccc",4);
System.out.println(t);

}

}


output:


{ccc=4, BBB=2, AAA=1}



No comments:

Post a Comment