Suppose I want to sort a list of Employee
objects:
Employee emp1 = new Employee("Abhijit", 10);
Employee emp2 = new Employee("Aniket", 5);
Employee emp3 = new Employee("Chirag", 15);
List<Employee> employees = new ArrayList<Employee>();
employees.add(emp1);
employees.add(emp2);
employees.add(emp3);
Collections.sort(employees);
System.out.println("sorted List is: "+employees);
And my Employee
class implements Comparable
, therefore it must override the compareTo()
method.
And I have to write my sorting logic in the compareTo()
method.
class Employee implements Comparable<Employee>
{
String name;
int empId;
public Employee(String name, int empId)
{
this.name= name;
this.empId = empId;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getEmpId()
{
return empId;
}
public void setEmpId(int empId)
{
this.empId = empId;
}
@Override
public int compareTo(Employee e)
{
// TODO Auto-generated method stub
return this.empId > e.empId ? 1 : (this.empId < e.empId ? -1 : 0);
//return 0;
}
@Override
public String toString()
{
return String.valueOf(empId);
}
}
How does sort()
call the compareTo()
method internally?
Please see open jdk source codes. I guess it helps.
java.util.Collections:
Collections sort calls Arrays.sort
java.util.Arrays:
Arrays.sort calls Arrays.mergeSort and your answer is on the line 1157.