Tuesday, March 3, 2015

Key Differences Between Comparator And Comparable In Java

 Comparator and comparable are important interfaces in Java API, they are used for comparison. Sometimes newbies are confused about use case of these two interfaces as they both are used for comparison. Both are used for sorting list of objects in Java. However, there are some major differences between comparable and comparator. Today we have listed six key differences between these two interfaces in Java API.
java, api, java api, comparator, comparable, java interfaces, comparator vs comparable, compareTo (), compare ().



1. Comparator interfaces is in utility class, it is located in java.util package. While, comparable interface is located in java.lang package which is essential for Java objects.

2. The syntax of Comparable includes ‘compareTo (Object toCompare)’ which means it accepts an object and uses Generics from Java 1.5 onwards. Where as the syntax for Comparator defines ‘compare(Object obj1, Object obj2) which is method for comparing two objects.

3. Comparator is used to compare current object represented by the keyword with another object. While, Comparator can compare two arbitrary objects passed to ‘compare()’ method in Java.

4. The key difference in Comparator and Comparable is, you can use only one compareTo() for an object. However it is possible to use multiple Comparator for comparing objects on different parameters.

5. Many Java classes use Comparator and Comparable for comparison defaults to ‘Comparable’ as it provides overloaded method to work with any arbitrary Comparator. For example, Collections.sort() method is used to sort collections in Java, they can either be sorted in natural order by using java.lang.Comparable or by using an implementation which accepts java.util.Comparator interface.

6. Both compareTo () and compare () methods in Java are used with equals () implementation. Hence, the return has to be zero. If two methods are equal by equals() method than compareTo () and compare () must return zero. If your implementation fails to follow this guideline, they object may break invariants of Java collection classes which rely on compare () or compareTo (). 




Courtesy:- EFYTIMES News Network

No comments:

Post a Comment