Difference between Comparator and Comparable in java - Java @ Desk

Thursday, May 23, 2013

Difference between Comparator and Comparable in java


Comparator Comparable
Class whose objects which we need to sort do not need to implement any interface method. Class whose objects which we need to sort must implement java.lang.Comparable interface compareTo(Object o1) method
The implementation to sort an object will be in different class The implementation to sort an object need to be in the same class
Multiple sort sequence can be created Single sort sequence allowed
java.lang.Comparator: int compare(Object o1, Objecto2)
This method compares o1 and o2 objects. Returned int value has the following meanings.
1. positive – o1 is greater than o2
2. zero – o1 equals to o2
3. negative – o1 is less than o1
java.lang.Comparable: int compareTo(Object o1)
This method compares this object with o1 object. Returned int value has the following meanings.
1. positive – this object is greater than o1
2. zero – this object equals to o1
3. negative – this object is less than o1


For sample implementation of Comparator, click here

For sample implementation of Comparable, click here






No comments:

Post a Comment