Collection Framework in JAVA 6
Comparator Interface
In Java, Comparator interface is used to order the object in your own way. It gives you ability to decide how element are stored within sorted collection and map.
Comparator Interface defines compare() method. This method compare two object and return 0 if two object are equal. It returns a positive value if object1 is greater than object2. Otherwise a negative value is return. The method can throw a ClassCastException if the type of object are not compatible for comparison.
Example of Comparator Interface
Student class
class Student
int roll;
String name;
Student(int r,String n)
{
roll = r;
name = n;
}
public String toString()
{
return roll+" "+name;
}
MyComparator class
This class defines the comparison logic for Student class based on their roll. Student object will be sotred in ascending order of their roll.
class MyComparator implements Comparator
{
public int compare(Student s1,Student s2)
{
if(s1.roll == s2.roll) return 0;
else if(s1.roll > s2.roll) return 1;
else return -1;
}
}
public class Test
{
public static void main(String[] args)
{
TreeSet< Student> ts = new TreeSet< Student>(new MyComparator());
ts.add(new Student(45, "Rahul"));
ts.add(new Student(11, "Adam"));
ts.add(new Student(19, "Alex"));
System.out.println(ts);
}
}
Output : [ 11 Adam, 19 Alex, 45 Rahul ]
As you can see in the ouput Student object are stored in ascending order of their roll.
Dinesh Kumar S is a 23-year-old System Administrator who enjoys playing games, listening to music and learning new technology. He is friendly and generous, but can also be very lazy and crazy.
Share this
Learn-JAVA