Javatpoint Logo

what is difference between comparator and comparable in java

By: kayala*** On: Tue Mar 05 08:51:42 IST 2013     Question Reputation0 Answer Reputation0 Quiz Belt Series Points0  0Blank User
javaUp0Down

 
1) Comparator in Java is defined in java.util package while Comparable interface in Java is defined in java.lang package.
2) Comparator interface in Java has method public int compare (Object o1, Object o2) which returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second. While Comparable interface has method public int compareTo(Object o) which returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.
3) If you see then logical difference between these two is Comparator in Java compare two objects provided to him, while Comparable interface compares "this" reference with the object specified.
4) Comparable in Java is used to implement natural ordering of object. In Java API String, Date and wrapper classes implement Comparable interface.
Image Created0Down

By: [email protected] On: Tue Mar 05 12:58:48 IST 2013 Question Reputation0 Answer Reputation392 Belt Series Points0 392User Image
Are You Satisfied :0Yes0No