Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Adding to Treeset

 
Mary John
Ranch Hand
Posts: 109
  • Mark post as helpful
  • send pies
  • 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.*;
 
ahmed yehia
Ranch Hand
Posts: 424
  • Mark post as helpful
  • send pies
  • 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.
 
Anonymous
Ranch Hand
Posts: 18944
  • Mark post as helpful
  • send pies
  • 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
  • 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
  • Quote
  • Report post to moderator
Here is the code again with identation and added compareTo, toString()

[ October 11, 2007: Message edited by: Ahmed Yehia ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic