I have a class Employee implementing Comparable interface
public class Employee implements Comparable<Employee> {
private int id;
private String name;
private int age;
private long salary;
public Employee(int id, String name, int age, int salary) {
this.id = id;
this.name = name;
this.age = age;
this.salary = salary;
}
@Override
public int compareTo(Employee emp) {
return (this.id - emp.id);
}
@Override
public String toString() {
return "[id=" + this.id + ", name=" + this.name + ", age=" + this.age + ", salary=" +
this.salary + "]";
}
}
I have a Employee[]
array I am sorting the array using Arrays.sort()
Employee[] empArr = new Employee[4];
empArr[0] = new Employee(10, "Mikey", 25, 10000);
empArr[1] = new Employee(20, "Arun", 29, 20000);
empArr[2] = new Employee(5, "Lisa", 35, 5000);
empArr[3] = new Employee(1, "Pankaj", 32, 50000);
Arrays.sort(empArr);
My question is how is sorting working internally,
is it like emArr[0].compareTo(emArr[1])
then swap the element if required?
I want to know how comparison and swapping are happening inside? and what role does Comparatable's compareTo(Object o)
and Comparator's compare(o1,o2)
are playing ?
There are already Sorting techniques for arranging any collection of items in an order. Java utility classes like Arrays, Collections use these techniques. For any such sorting technique to work it is important to define how to decide which of the two objects are greater.
This information is provided in the implementation of compareTo()
in case of the Object's class implements Comparable
interface.
This information can also be provided in the implementation of compare()
method of the Comparator
class. Comparator class is useful in case you want to define different ordering as per the requirement (may be based on some parameter during run time). It may be possible that the class of the entity implements Comparable interface but we want for some specific case the sorting to be of different order or based on some other parameter.
Read more on Comparable
https://docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html
and Comparator
https://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html