File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
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 Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Adding to Treeset" Watch "Adding to Treeset" New topic

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.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.
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 ]
I agree. Here's the link:
subject: Adding to Treeset
It's not a secret anymore!