• 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

Question 10 Chapter 7 : K and B

 
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Exception in thread "main" java.lang.ClassCastException: java.lang.Object cannot be cast to java.lang.Comparable


I tried compiling the above prog but got this exception :

Exception in thread "main" java.lang.ClassCastException: java.lang.Object cannot be cast to java.lang.Comparable
 
Ranch Hand
Posts: 317
Eclipse IDE
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
You need to add object which implements the comparable interface of. This is the default implementation of the add method.
Below is the excerpt from API

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Yes, TreeSet is sorted collection and must have elements that implement compareTo() from interface Comparable. That is how TreeSet will know where to add() the new elements.
 
Ranch Hand
Posts: 310
1
Oracle Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

Rahul Manikuntla wrote:Yes, TreeSet is sorted collection and must have elements that implement compareTo() from interface Comparable. That is how TreeSet will know where to add() the new elements.

Exactly! In

you are adding a String and an Object o. String, Wrappers, Date classes implement Comparable by default. But cannot add a plain "Object o" which hasn't implemented Comparable.
 
Sheriff
Posts: 9707
43
Android Google Web Toolkit Hibernate IntelliJ IDE Spring Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It is not necessary that the objects that we add to a TreeSet implement Comparable. If we use a Comparator, then we can add elements to the TreeSet which don't implement Comparable. Eg:-
The rule is, the elements that we add to the TreeSet must be comparable to each other...
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic