Difference between Comparator and Comparable.

Comparator and Comparable both are used to sort collection of object by its property.

Comparator sorting example.

Object that needs to be sorted doesnt need to implement Comparable. Other class than implement this interface.

public sortEmployeeByEmployeeIdComparator implements Comparator<Employee>{

@Override

public int compare{

return (this.employeeId < employee.employeeId)?-1:(this.employeeId > employee.employeeId)?1:0;

}}

 

 

Comparable sorting example.

public class Employee implements Comparable{

@Override

public int CompareTo(Object arg){

Employee employee = (Employee)arg;

return (this.employeeId < employee.employeeId)?-1:(this.employeeId > employee.employeeId)?1:0;

}}

If any class implements Comparable interface then collection of that object can be sorted automatically using Collection.sort() or Arrays.sort().

Leave a Reply

Your email address will not be published. Required fields are marked *