Monday, 21 April 2014

collections---------------treeset----------------comparator

import java.util.*;
class MyComparator implements Comparator
{
    public int compare(Object obj1,Object obj2)
    {
        Integer i1=(Integer) obj1;
        Integer i2=(Integer) obj2;
        //return i1.compareTo(i2);//Ascending Order
        //return -i1.compareTo(i2);//Dscending Order
        //return +1;//INSERTION ORDER
        return -1;//REVERSE INSERTION ORDER
       
    }
}
class  CustomTreeSetDemo//follows dictionary order but we can customize using comparatot interface.
{
    public static void main(String[] args)
    {
        TreeSet ts=new TreeSet(new MyComparator());
        ts.add(10);//doesn't follwo insertion order
        ts.add(20);
        ts.add(50);
        ts.add(20);//don't allows duplicate values
        ts.add(40);
        ts.add(30);
        ts.add(70);
       
        ts.add(60);
       

        System.out.println(ts.add(20));//false
        //System.out.println(ts.add(null));//allow one time get R.E. i.e. Exception in thread "main" java.lang.NullPointerExceptio
       

        //ts.add("a");//hetero geneous objects are allowed.
        //R.E. i.e. Exception in thread "main" java.lang.ClassCastException: java.lang.Integer canno
        //t be cast to java.lang.String
        //at java.lang.String.compareTo(Unknown Source)
        //at java.util.TreeMap.put(Unknown Source)
        //at java.util.TreeSet.add(Unknown Source)
       //at TreeSetDemo.main(TreeSetDemo.java:20)
       
        System.out.println(ts);
    }
}

1 comment: