- Java supports sorting of many types of objects. To sort a list of objects, it is necessary to have some “ordering” on the objects.
- Comparator and Comparable interfaces are used to maintain the order of objects.
- Allows you to compare objects based on the primary field. once set you do not have the option to change the primary field.
class Person implements Comparable<Person>{
public String name;
public Double salary;
public Person(String name,Double salary){
this.name = name;
this.salary = salary;
}
@Override
public int compareTo(Person p){
if(this.salary.compareTo(p.salary) == 0){
return this.name.compareTo(p.name);
}
return this.salary.compareTo(p.salary);
}
}- Provides a more flexible way to compare objects.
class Person {
public String name;
public Double salary;
public Person(String name, Double salary) {
this.name = name;
this.salary = salary;
}
}
class NameComparator implements Comparator<Person>{
@override
public int compare(Person p1, Person p2){
return p1.name.compareTo(p2.name);
}
}
class SalaryComparator implements Comparator<Person>{
@override
public int compare(Person p1, Person p2){
return p1.salary.compareTo(p2.salary);
}
}
class Main{
public static void main(){
Person[] p = new Person[] {
new Person("john",23998.88),
new Person("sam",45678.33)
};
Arrays.sort(p); // sorts using compareTo method
Arrays.sort(p,new NameComparator()); // sorting using name
Arrays.sort(p,new SalaryComparator()); // sorting using salary
}
}It must be true that:
- a is “less than” b if and only if b is “greater than” a
- if a is “less than” b and b is “less than” c, then a must be “less than” c.
- It should also be true that the Comparator is consistent with equals; in other
words:
compare(a,b) == 0 if and only if a.equals(b)
- List Containers use the
equalsmethod to check containment (list.contains(obj)). - Containers Maintaining Order like
TreeSetuse theComparator'scomparemethod for containment (treeSet.contains(obj)). - A
Comparatorshould be consistent with theequalsmethod to ensure expected behavior across different container implementations and avoid inconsistencies or unexpected results, especially when dealing with sorted containers likeTreeSet.