Main differences between Comparable and Comparator are:
1. Type: Comparable
the type of objects that this object may be compared to.
2. Comparator
objects that may be compared by this comparator.
3. Sorting: In Comparable, we can only create one sort
sequence. In Comparator we can create multiple sort
sequences.
4. Method Used: Comparator
method public int compare (Object o1, Object o2) that
returns a negative integer, zero, or a positive integer when
the object o1 is less than, equal to, or greater than the
object o2. A Comparable
int compareTo(Object o) that returns a negative integer,
zero, or a positive integer when this object is less than,
equal to, or greater than the object o.
5. Objects for Comparison: The Comparator compares two
objects given to it as input. Comparable interface
compares "this" reference with the object given as input.
6. Package location: Comparable interface in Java is defined
in java.lang package. Comparator interface in Java is
defined in java.util package
xxxxxxxxxx
class TestComparator{
public static void main(String args[]){
//Creating a list of students
ArrayList<Student> al=new ArrayList<Student>();
al.add(new Student(101,"Vijay",23));
al.add(new Student(106,"Ajay",27));
al.add(new Student(105,"Jai",21));
System.out.println("Sorting by Name");
//Using NameComparator to sort the elements
Collections.sort(al,new NameComparator());
//Traversing the elements of list
for(Student st: al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
System.out.println("sorting by Age");
//Using AgeComparator to sort the elements
Collections.sort(al,new AgeComparator());
//Travering the list again
for(Student st: al){
System.out.println(st.rollno+" "+st.name+" "+st.age);
}
}
}