My understand is Comparator can compare multiple objects from different classes while Comparable can only compare one onject with another instance in the same class.
C
I think that when we want compare a user defined class by multiple attribute naturally ,is better that we use from Comparator interface that permitted us create some classes that implemented comparator interface and compare each one of attributes.in this case we have a below code :
public class Student{
private String name;
private String ranking;
private int age;
private String country;
// getter and setter
}
public class NameComparator implements Comparator{
//compare by name attribute
}
public class AgeComparator implements Comparator{
//compare by Age attribute
}
public class CountryComparator implements Comparator{
//compare by Country attribute
}
public class RankingComparator implements Comparator{
//compare by Ranking attribute
}
But when we want compare a user defined class by using just one attribute There is no need to comparator , instead of it we can use comparable interface as below code:
public class Student{
private String name;
private String ranking;
private int age;
private String country;
// getter and setter
public int CompareTo(Object obj1){
//implement comparation by name or age or etc
}
}
And one of the place that is good , if we used from Comparator interface is for built in classes that have implemented CompareTo method such as number and etc.