• 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:
  • Tim Cooke
  • Campbell Ritchie
  • paul wheaton
  • Ron McLeod
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Liutauras Vilda
  • Paul Clapham
Saloon Keepers:
  • Tim Holloway
  • Carey Brown
  • Piet Souris
Bartenders:

Adding to Treeset

 
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
The following code for adding elements to Treeset Compiles but gives the exception at runtime

Exception is thread main java.lang.classCastException
at TreeMap.compare
at TreeMap.put
at TreeSet.add


Can you please explain why???

Thanks in Advance


import java.util.*;
 
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
This is because you are using TreeSet, which requires that its elements should implement the Comparable interface in order to sort them.
 
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi ,

As Ahmed suggested, it should implement Comparable interface for Treeset to work and also I guess, you need to check your equals method, as Set does not allow duplicate values. You should override equals method, and that way you can determine whether the newly being added object is already existing or not. Please some one let me know, if this is not a requirement.
 
ahmed yehia
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Hi Chandra
Implementing Comparable and overriding compareTo() is enough to get elements in the TreeSet so it can sort them. And as equals() is not overriden so the default inherited implementation will be used which will check refrences.
 
ahmed yehia
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Here is the code again with identation and added compareTo, toString()

[ October 11, 2007: Message edited by: Ahmed Yehia ]
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic