| Author |
Regarding collections
|
kiruthigha rajan
Ranch Hand
Joined: Dec 29, 2011
Posts: 69
|
|
|
can anyone please explain the difference between comparator and comparable interface..please explain in detail with example.thanks in advance
|
 |
Henry Wong
author
Sheriff
Joined: Sep 28, 2004
Posts: 16684
|
|
kiruthigha rajan wrote:can anyone please explain the difference between comparator and comparable interface..please explain in detail with example.thanks in advance
Have you taken a look at the JavaDocs? ... java.lang.Comparable and java.util.Comparator ... the first enables an object to be compared to any other object, while the second should be implemented by a third object that can be used to compare any two objects.
Henry
|
Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
|
 |
Matheus Souza
Ranch Hand
Joined: Mar 06, 2012
Posts: 38
|
|
kiruthigha rajan wrote:can anyone please explain the difference between comparator and comparable interface..please explain in detail with example.thanks in advance
Well, anyone correct me if I am wrong. Comparable is an interface that need to be declared in the class you want to compare, and you need to implement the compareTo(Object) method. Whereas Comparator is an interface that allows you to create another class to make this comparation for you through the compare(Object, Object) methos, and you can implement more than one compare method, instead of Comparable that allows you just one implementation. In orther words, the comparator let's up to you where you want to implement the comparation method and implement as many comparation methods as necessary.
|
 |
Javin Paul
Ranch Hand
Joined: Oct 15, 2010
Posts: 276
|
|
1. Comparable is about natural ordering where one object compare itself with another., Comparator is about any order.
2. Most of sorted set and map use Comparable if no Comparator is defined.
3. Recommended that value Object should implement Comparable, JDK does that see String, Integer all implements Comparable.
4. While overriding compareTo() method for Comparable make sure its consistent with equals() method. means if two object are equal by equals method than compareTo() must return zero. failing this your object may violate general contract of SortedSet and SortedMap which uses compareTo() for duplicate checking.
See if this helps: http://javarevisited.blogspot.com/2011/06/comparator-and-comparable-in-java.html
|
http://javarevisited.blogspot.com - java classpath - Java67 - java hashmap - java logging tips java interview questions Java Enum Tutorial
|
 |
 |
|
|
subject: Regarding collections
|
|
|