sample code to demonstrate comparator Interface
package collection;
import java.util.Comparator;
import java.util.TreeSet;
public 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);
}
}
output:
[aaa, bbb, ccc, ddd]
0 comments:
Post a Comment