I have an Employee class which has 3 fields like below.
class Employee
{
private int empId;
private String empName;
private int empAge;
public Employee(int empId, String empName, int empAge) {
this.empId = empId;
this.empName = empName;
this.empAge = empAge;
}
// setters and getters
For this I want to sort based on Employee Name(empName), if multiple employees have the same name, then sort based on employee id(empId).
For this I have written a custom comparator using java.util.Comparator like below.
class SortByName implements Comparator<Employee>
{
public int compare(Employee o1, Employee o2) {
int result = o1.getName().compareTo(o2.getName());
if (0 == result) {
return o1.getEmpId()-o2.getEmpId();
} else {
return result;
}
}
}
I have created 8 Employee objects and added to an ArrayList like below.
List<Employee> empList = new ArrayList<Employee>();
empList.add(new Employee(3, "Viktor", 28));
empList.add(new Employee(5, "Viktor", 28));
empList.add(new Employee(1, "Mike", 19));
empList.add(new Employee(7, "Mike", 19));
empList.add(new Employee(4, "Mark", 34));
empList.add(new Employee(6, "Jay", 34));
empList.add(new Employee(8, "Gayle", 10));
empList.add(new Employee(2, "Gayle", 10));
And sorted the list like below using the above comparator.
Collections.sort(empList,new SortByName());
It has worked absolutely fine. But this can be done using Comparable also like below.
class Employee implements Comparable<Employee> {
private int empId;
private String name;
private int age;
public Employee(int empId, String name, int age) {
this.empId = empId;
this.name = name;
this.age = age;
}
//setters and getters
@Override
public int compareTo(Employee o) {
int result = this.getName().compareTo(o.getName());
if (0 == result) {
return this.getEmpId()-o.getEmpId();
} else {
return result;
}
}
}
Sort the list using Collections.sort(empList);
So I want to know what is the use case or where exactly we use these both? I understood that Comparable is used for natural sorting and can sort using only one field and comparator is used for multiple fields sorting. But if we see my example both the interfaces has the capability to do these both. So please explain me what are the unique features of these both where other one can't be used.
If you really want to know the unique feature of both.
Implementing Comparable let you compare your Class to an other Class.
A Comparator is an algorithm to compare two instances of a same Class type.