• 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

Doubt about Treeset

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


This code compiles fine, but at runtime gives ClassCastException.

Is it because the class Person does not have equals() and hashcode() methods defined ?
 
Ranch Hand
Posts: 50
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi,

the problem is that your class Person doesn't implement the Comparable interface. Therefore instances of the Person can't be sorted while adding to the TreeSet.
 
Ranch Hand
Posts: 637
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
add() API of TreeSet class
Throws:
ClassCastException - if the specified object cannot be compared with the elements currently in the set.

Your Person class does not implement Comparable interface and implement the comaareTo() of Comparable interface. Hence add() fails to add Person object and throws ClassCastException.

Note that ClassCastException is thrown only when you add more than 2 elements to the set. Its when you add second element, the second element will be compared to the first element, and since the class Person does not implement Comparable interface and hence ClassCastException is thrown.

Thanks
Deepak
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic