• 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
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

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: 23951
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
 
Attractive, successful people love this tiny ad:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com
reply
    Bookmark Topic Watch Topic
  • New Topic