This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Adding to Treeset Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Adding to Treeset" Watch "Adding to Treeset" New topic
Author

Adding to Treeset

Mary John
Ranch Hand

Joined: Sep 17, 2007
Posts: 109
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.*;


SCJP 5.0<br />SCJD working on it
ahmed yehia
Ranch Hand

Joined: Apr 22, 2006
Posts: 424
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

Joined: Nov 22, 2008
Posts: 18944
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

Joined: Apr 22, 2006
Posts: 424
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

Joined: Apr 22, 2006
Posts: 424
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.
 
subject: Adding to Treeset