This post will help u if u have trouble with sorting class instances by different data fields. Also distinction between Comparable & Comparator Interfaces is show.
java.util.Arrays has many overloaded sorting methods. Simply if you want to sort any primitive type like int, boolean, char, long, double
java.util.Arrays.sort(arr);
where arr is array name!
It will use QuickSort for any primitive type.
What if the array of non-primitive type :-
Eg. Suppose you want to sort an array emp[] of type Employee class given below
public class Employee{
int id,salary,yearOfJoining;
}
(The problem here is Arrays.sort() doesn’t know how to compare two Employees)
There are two ways according to the requirement :-
1. Comparable Interface
Comparable Interface has only one method
int compareTo(Object );
Arrays.sort() method implicitly calls compareTo(Object ) method when the array is of non-primitive type to compare two Objects.
So one just has to add an additional method to class definition.
Eg.
public class Employee{
int id, salary, yearOfJoining;
public Employee(int id,int salary,int yearofJoining){
this.id = id; this.salary = salary; this.yearofJoining = yearofJoining;
}
int compareTo(Object x){
return this.id - ((Employee) x).id;
}
}
public class Main{
public static void main(String args[]){
int n = 8;
Employee es[n] = new Employee[n];
for(int i=0;i<n;i++){
es[i] = new Employee(n-i,100000-i*1000,2011-i);
}
Arrays.sort(es);
}
}
Arrays.sort() method will sort the array with respect to employees’ ids!
2. Comparator Interface
If one wants to sort by different data members, then one must use Comparators as shown below…
Comparator Interface also has only one method
int compare(Object , Object);
But the Use of Comparator is phenomenon. Suppose now you want to sort the given array with respect to their salaries or by their yearOfJoining.
One can’t write other compareTo() method.
Here the Comparator comes Handy!
Arrays.sort(Object arr[], Comparator obj)
is the method using different Comparators.
Eg.
public class Employee{
int id, salary, yearOfJoining;
}
public class bySalary implements Comparator<Employee>{
int compare(Employee one, Employee two){
return one.salary-two.salary;
}
}
public class byYearOfJoining implements Comparator<Employee>;{
int compare(Employee one, Employee two){
return one.yearOfJoining - two.yearOfJoining;
}
}
When you want to sort by Salary
Arrays.sort(array, new bySalary<Employee>())
and when by yearOfJoining
Arrays.sort(array, new byYearOfJoining<Employee>())
This is because overloaded sort method expects a comparator object.
For non-primitive types Arrays.sort() method uses MergeSort to make sure the time complexity remains O(nlogn).
“The most important property of a program is whether it accomplishes the intention of its user.”
― C.A.R. Hoare
Keep Coding
Manish M Berwani