In case of Comparable interface,
- The object o1 (class of which implements the interface) is compared to the object o2 which is passed as method argument [NOTE: public int compareTo(Object o2) ]
- If the o1 is greater than o2 then the method will return +ve integer and -ve if lesser than o2, if both are equal then 0 value is returned.
- It should be used when you want to define natural/default ordering of a class, if the class is available for modification (remember? a third party class isn't available for modification)
- if one add two keys a and b such that (!a.equals(b) && a.compareTo(b)==0) to a sorted set that does not use an explicit comparator, then the second add operation returns false (and the size of the sorted set does not increase) because a and b are equivalent from the sorted set's perspective.
In case of Comparator interface,
- The Class which implements this interface will take two objects and compare them with each other. [NOTE: public int compare(Object o1, Object o2)
- If the o1 is greater than o2 then the method will return +ve integer and -ve if lesser than o2, if both are equal then 0 value is returned.
- If the class isn't available for modifying or if you want to define ordering which is other than the default then use the Comparator interface.
- If one add two keys a and b such that (a.equals(b) && c.compare(a,b)!=0) to a sorted set with comparator c, then the second add operation returns false (and the size of the sorted set does not increase) because a and b are equivalent from the sorted set's perspective.
Resources
- http://grdurand.com/static/presentation_four/comparable.html
- http://lkamal.blogspot.com/2008/07/java-sorting-comparator-vs-comparable.html
- http://leepoint.net/notes-java/data/expressions/22compareobjects.html
- http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Comparable.html
- http://download.oracle.com/javase/1.4.2/docs/api/java/util/Comparator.html
No comments:
Post a Comment
Please use proper blogging etiquette while posting comments.
Note: only a member of this blog may post a comment.