Thursday, March 5, 2009

example code TreeMap comparator

package myutil;

import java.util.Comparator;
import java.util.TreeMap;
class Mycompare implements Comparator
public int compare(Object o1,Object o2)
Integer i1=(Integer)o1;
Integer i2=(Integer)o2;
return -i1.compareTo(i2);

public class TreeMapCom {
public static void main(String[] args)
TreeMap map=new TreeMap(new Mycompare());
map.put(new Integer(100),"orange");
map.put(new Integer(300),"apple");
map.put(new Integer(200),"grapes");
map.put(new Integer(400),"grapes");
System.out.println("The TreeeMap Is "+map);
// Try to place the null you will get NullPointerException

The TreeeMap Is {400=grapes, 300=apple, 200=grapes, 100=orange}

Post a Comment