Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Regarding collections

 
kiruthigha rajan
Ranch Hand
Posts: 69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
can anyone please explain the difference between comparator and comparable interface..please explain in detail with example.thanks in advance
 
Henry Wong
author
Marshal
Pie
Posts: 22104
88
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Matheus Souza
Ranch Hand
Posts: 38
Eclipse IDE Java Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 295
Eclipse IDE Firefox Browser Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic