File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
Win a copy of Soft Skills: The software developer's life manual this week in the Jobs Discussion forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparable or Comparator

 
Nabila Mohammad
Ranch Hand
Posts: 661
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is a question from John Meyers Mock paper.



The result of this code is a Runtime Exception (ClassCastException)

The explanation written is it needs to implement Comparable rather than Comparator to be able to sort its objects automatically. A RuntimeClassCastException is thrown.


And Another code with the same Exception



My question is how do I decide what is supposed to be used - Comparator or Comparable?
And that it might throw an Exception.
Does this means Set is always supposed to implement Comparable Interface
 
Henry Wong
author
Marshal
Pie
Posts: 20820
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
My question is how do I decide what is supposed to be used - Comparator or Comparable?
And that it might throw an Exception.
Does this means Set is always supposed to implement Comparable Interface


If you take a look at the interfaces, and some examples on how they are to be used (correct examples, that is), you will notice that they are not the same thing.

The comparable interface is used by data objects to allow it to be compared to other objects. And the comparator is an external object that compares two objects. They work differently. One rely on the data object to compare itself to others. The other is a comparator object that compares data objects.

The TreeSet collection supports both. You can add comparable objects into the set, and the set will sort them. Or you can assign an external comparator, via a constructor, when the TreeSet is instantiated, and add any object (supported by the comparator) to the set.

Henry
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic