These are the two interfaces mainly provided to achieve sorting on the basis of comparisons among the objects on the basis of custom/self imposed conditions.
Comparable in Java is used to compare an object with another objects, whereas Comparator is used for comparing different objects.
Comparable uses compareTo(arg) method for sorting the data whereas Comparator uses compare(arg1, arg2) method.
Comparable is used bydefault when Collections.sort() or Arrays.sort() is used for sorting whereas Comparator needs to be mentioned whenever we are going to use it for sorting.
//comparable
Collections.sort(list)
//comparator
Collections.sort(list,comparator)
Comparable is in java.lang package and Comparator is in the java.util package.
Comparable modify the actual class but comparator doesn't affect the actual class.
Comparable is single sorting technique it means the sorting can be done on the basis of one attribute/element of an object and Comparator is multiple sorting technique which means sorting can be done on the basis of multiple attributes/elements of object.
public class MyEmployees {
private int id;
private String name;
private int salary;
// constructor, setters, getters
}
//comparable
public class MyEmployees implements Comparable<MyEmployees> { @Override
public int compareTo(MyEmployees otherEmployee) {
return Integer.compare(getSalary(), otherEmployee.getSalary());
}
}
//comparator
public class MyEmployeesComparator implements Comparator<MyEmployees> { @Override
public int compare(MyEmployees firstEmployee, MyEmployees secondEmployee) {
return Integer.compare(firstEmployee.getSalary(), secondEmployee.getSalary());
}
}
Comentários