Java : Comparable Vs Comparator


Comparable and Comparator both are interface used for compare and sorting collections of objects. Where  Comparable used for natural ordering of objects while Comparator used for sorting on user specific value on different type objects. In both the cases if objects are not equate or compatible will through ClassCastException.

In below links, I have explained about in depth detail about Comparable and Comparator implementation and cases where to use. Here mainly focus on some points for technical, implementation and functional points.

Comprable :Sort ArrayList in Ascending or Descending Order or Natural or Chronological Order

How to Sort By Comparable Interface in Ascending and Descending Order : Java

How to sort object by Comparator interface in ascending and descending order : JAVA

Difference between Comparable and Comparator

Comparable Comparator
Comparable is in java lang package as java.lang.Comparable. Comparator is in java util package as java.util.Comparator.
Method used int compareTo(Object t); Method used int compare(Object t1 , Object t2);

Comparable is used to compare itself by using with another object.

Here modify the class whose instance you want to sort. So that only one sort sequence can be created per class.

Comparator is used to compare two datatypes are objects.

Here build a class separate from class whose instance you want to sort. So that multiple sort sequence can be created per class.

 A comparable used for default and natural ordering of objects.  A comparator represents the ordering itself for specific use.

Some java classes having build in Comparable interface like String, Date, Wrapper Classes etc.

Some classes actually provide Comparators for common cases; for instance, Strings are by default case-sensitive when sorted, but there is also a static Comparator called CASE_INSENSITIVE_ORDER.
 For sorting use methods like Collections.Sort(List) or Array.sort().  For Sorting use method Collections.sort(List, Comparator).

Reference :

https://docs.oracle.com/javase/tutorial/collections/interfaces/order.html

Advertisements

About Saurabh Gupta

My Name is Saurabh Gupta, I have approx. 10 Year of experience in Information Technology World manly in Java/J2EE. During this time I have worked with multiple organization with different client, so many technology, frameworks etc.
This entry was posted in Collection, Collections, Example, Java, Sort and tagged , , , , , , , . Bookmark the permalink.