Help coderanch get a
new server
by contributing to the fundraiser
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Ron McLeod
  • Paul Clapham
  • Devaka Cooray
  • Liutauras Vilda
Sheriffs:
  • Jeanne Boyarsky
  • paul wheaton
  • Henry Wong
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Tim Moores
  • Carey Brown
  • Mikalai Zaikin
Bartenders:
  • Lou Hamers
  • Piet Souris
  • Frits Walraven

Comparable or Comparator

 
Ranch Hand
Posts: 664
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
author
Posts: 23956
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic