Sunday, February 15, 2009

Comparator tutorial - Example code

Comparator Interface:
If you want to define our own sorting we havwet to implement comparator interface.
This interface present in java.util package.
This interface contain the following two methods.
1.public int compare(Object o1,Object o2)
return –ve number if o1 comes before o2.
Return +ve number If o1 comes after o2.
Returns zero if o1 and o2 equal.
2.public Boolean equals(Object o)
by using comparator interface we can define our own customized sorting.

Write a program to insert integer object in the TreeSet where the Sorting technique is descending order.
Import java.util.*;
Class TreeSetDemo
{
Public static void main(String arg[])
{
TreeSet t=new Treeset(new MyComparator());
t.add(new Integer(20));
t.add(new Integer(10));
t.add(new Integer(30));
t.add(new Integer(100));
System.out.println(t); // 10 ,20 ,30,100
}
}
class MyComparator implements Comparator
{
public int Compare(Object o1,Object o2)
{
Integer i1=(Integer)o1;
Integer i2=(Integer)o2;
Int i1=i1.intValue();
Int i2=i2.intValue();
If(i1>i2)
return -1;
else
If(i1 > i2)
return +1;
else
return 0;
}
}

write a program to insert string objects into the TreeSet where the sorting order is increasing order of String lengths.
Import java.util.*;
Class ComparatorDemo
{
public static void main(String arg[])
{
TreeSet t=new Treeset(new Mycomparator())
t.add(“aaaaaa”);
t.add(“bbbb”);
t.add(“ccc”);
System.out.println(t); // [ccc,bbbb,aaaaaa]
}
}
class MyComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
String s1=(String)o1;
String s2=(String)o2;
if(s1.length() < s2. length())
return -1;
else
if(s1.length() > s2.length())
return +1;
else
return 0;
}
}
WAP to insert StringBuffer Objects in the treeSet according to dictionary order
Import java.util.*;
Class ComparatorDemo
{
public static void main(String arg[])
{
TreeSet t=new TreeSet(new MyComparator());
t.add(new StringBuffer(“aaa”);
t.add(new StringBuffer(“bbb”);
t.add(new StringBuffer(“ccc”);
t.add(new StringBuffer(‘ddd”);
System.out.println(t);
}
}
class MyComparator implements Comparator
{
public int compare(Object o1,Object o2)
{
String s1=o1.toString();
String s2=o2.toString();
return s1.compareTo(s2);
//return s2.compareTo(s1);
}
}
if we return always like this:
return 0; // aaa
return +100 // bbb,ccc,aaa,ddd
return -100 // ddd,aaa,ccc,bbb

0 comments:

Post a Comment