Skip to content

Latest commit

 

History

History
89 lines (68 loc) · 2.67 KB

File metadata and controls

89 lines (68 loc) · 2.67 KB

Comparable and Comparator Interface

  • 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.

Comparable Interface

  • 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);
    }
	
}

Comparator Interface

  • 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
    }
}

The compare contract for Comparators:

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)

Why comparator should be consistent with equals method ?

  • List Containers use the equals method to check containment (list.contains(obj)).
  • Containers Maintaining Order like TreeSet use the Comparator's compare method for containment (treeSet.contains(obj)).
  • A Comparator should be consistent with the equals method to ensure expected behavior across different container implementations and avoid inconsistencies or unexpected results, especially when dealing with sorted containers like TreeSet.