Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Comparable or Comparator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Comparable or Comparator" Watch "Comparable or Comparator" New topic
Author

Comparable or Comparator

Nabila Mohammad
Ranch Hand

Joined: Nov 05, 2007
Posts: 661
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


The future belongs to those who believe in the beauty of their dreams.Dream BIG!
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18494
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
 
subject: Comparable or Comparator
 
Similar Threads
TreeSet & Comparator
comparator comparable
Comparator and Compatable Query
Comparator Runtime Exception Help
Comparator