Usage of Comparable and Comparator is the most commonly asked Java interview question.
Java provides features for sorting Arrays and Collections by using respective sort method.
Sorting a String objects is straightforward there is no need to override any necessary methods,sorting is done based on comparison of certain properties . First we will see sorting of a LinkedList,a simple Collection..\
Example:-
The output of following code is
[India, America, China, Russia] Before Sorting
[America, China, India, Russia] After Sorting
If a particular objects need to be sorted their class should implement Comparable or comparator interface.
There is a difference in usage of both this interfaces which we will discuss at the end of this topic.
For now in order to sort objects based on single attribute we use Comparable interface.
Below example shows the sorting of three Employee objects based on employeeId
Source code for Employee class
Employee class extends comparable interface and we need to override compareTo(Object) method (line 29). The logic of comparing is described in the method.
this.employeeId-recentEmpId gives data in ascending order.
recentEmpId -this.employeeId gives data in descending order
Now we will create three Employee objects and insert them into a linked list and sort them.
Source code for EmployeeSort
As we discussed earlier reiterating the same for an object to be sorted the respective class should implement either Comparable or Comparator.Here Employee objects can be sorted.
Line no 10 to 12 we have created three employee objects ,16-18 adding employee objects to empList @28 using Collections.sort().
Output of the program:-
Before sorting
2 Amda amda@java-recent.com
3 Chetan chetan@java-recent.com
1 John john@java-recent.com
Before sorting elements are retrieved as per their order of insertion.
Sorted Employee List
1 John john@java-recent.com
2 Amda amda@java-recent.com
3 Chetan chetan@java-recent.com
Here result is sorted based on employeeId. The actual implementation is written in compareTo() method in Employee class
Just have a look at source code of Collections.sort() method
System.out.println(e1.getEmployeeName()+"\\ and //"+e2.getEmployeeName());
System.out.println( e1.getEmployeeName().compareTo(e2.getEmployeeName());
o/p
Amda\ and //John
-9
Chetan\ and //Amda
2
Chetan\ and //John
-7
Chetan\ and //Amda
2
The major difference between Comparable and Comparator
Using Comparator we can implement different sorting logics in different clases,then we pass it to Collections.sort([collections],new [class that have sorting logic]).
Example:- we have employee class ,then we write two sorting classed EmployeeNameSort,EmployeeEmailIdSort both of them implements Comparator interface.
On a same employee class we have implemented two different sorting logics,if we would have used Comparable we can implement only one sorting logic.
Java provides features for sorting Arrays and Collections by using respective sort method.
Sorting a String objects is straightforward there is no need to override any necessary methods,sorting is done based on comparison of certain properties . First we will see sorting of a LinkedList,a simple Collection..\
Example:-
The output of following code is
[India, America, China, Russia] Before Sorting
[America, China, India, Russia] After Sorting
The sort method is able to sort the String objects because the String class implements Comparable interface and overrides compareTo() method For String class source code refer String source code
Similarly Arrays.sort() also works on the same line.
Now the most important implementation is when we want to sort user defined objects .Suppose we have an Employee object having employeeId, employeeName and empMailId .we need to sort them based on different attributes it has.
Scenario-1:- Sorting Employee Object using comparable interface.
If a particular objects need to be sorted their class should implement Comparable or comparator interface.
There is a difference in usage of both this interfaces which we will discuss at the end of this topic.
For now in order to sort objects based on single attribute we use Comparable interface.
Below example shows the sorting of three Employee objects based on employeeId
Source code for Employee class
Employee class extends comparable interface and we need to override compareTo(Object) method (line 29). The logic of comparing is described in the method.
this.employeeId-recentEmpId gives data in ascending order.
recentEmpId -this.employeeId gives data in descending order
Now we will create three Employee objects and insert them into a linked list and sort them.
Source code for EmployeeSort
As we discussed earlier reiterating the same for an object to be sorted the respective class should implement either Comparable or Comparator.Here Employee objects can be sorted.
Line no 10 to 12 we have created three employee objects ,16-18 adding employee objects to empList @28 using Collections.sort().
Output of the program:-
Before sorting
2 Amda amda@java-recent.com
3 Chetan chetan@java-recent.com
1 John john@java-recent.com
Before sorting elements are retrieved as per their order of insertion.
Sorted Employee List
1 John john@java-recent.com
2 Amda amda@java-recent.com
3 Chetan chetan@java-recent.com
Here result is sorted based on employeeId. The actual implementation is written in compareTo() method in Employee class
Just have a look at source code of Collections.sort() method
public static <T extends Comparable<? super T>> void sort(List<T> list) { Object[] a = list.toArray(); Arrays.sort(a); ListIterator<T> i = list.listIterator(); for (int j=0; j<a.length; j++) { i.next(); i.set((T)a[j]); } } }
In the previous example we have sorted based on single attribute[employeeId].
Now we will see about comparator interface.
Now we will see about comparator interface.
Scenario-1:- Sorting Employee Object using comparator interface.
Comparator interface is used if we want to implement sorting logic in a different class.
The method used for implementing business logic is compare(Object obj1,Object 2).
Source code for EmployeeSortComparator
Comparator interface is used if we want to implement sorting logic in a different class.
The method used for implementing business logic is compare(Object obj1,Object 2).
Source code for EmployeeSortComparator
EmployeeSortComparator class implements Comparator interface and overrides
compare method which takes two parameters.we are comparing employee names.
Return values :-
positive if e1 is greater than e2
Zero if e1 equals e2
Negative if e1 is less than e2
Lets insert a syso statements in the above source codecompare method which takes two parameters.we are comparing employee names.
Return values :-
positive if e1 is greater than e2
Zero if e1 equals e2
Negative if e1 is less than e2
System.out.println(e1.getEmployeeName()+"\\ and //"+e2.getEmployeeName());
System.out.println( e1.getEmployeeName().compareTo(e2.getEmployeeName());
o/p
Amda\ and //John
-9
Chetan\ and //Amda
2
Chetan\ and //John
-7
Chetan\ and //Amda
2
The major difference between Comparable and Comparator
- Class Objects which we need to sort must implement Comparable interface
- Class Objects which we need to sort need not implement Comparator interface
Using Comparator we can implement different sorting logics in different clases,then we pass it to Collections.sort([collections],new [class that have sorting logic]).
Example:- we have employee class ,then we write two sorting classed EmployeeNameSort,EmployeeEmailIdSort both of them implements Comparator interface.
On a same employee class we have implemented two different sorting logics,if we would have used Comparable we can implement only one sorting logic.
No comments:
Post a Comment