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 Treeset Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Treeset" Watch "Treeset" New topic


Shanky Sohar
Ranch Hand

Joined: Mar 17, 2010
Posts: 1051

this program is from examlab..........
why this program is throwing classcast exception............
import java.util.TreeSet;

public class Test2{

public static void main(String args[])
TreeSet<Test2> at=new TreeSet<Test2>();
at.add(new Test2());
at.add(new Test2());
at.add(new Test2());

SCJP6.0,My blog Ranchers from Delhi
Henry Wong

Joined: Sep 28, 2004
Posts: 20531

Take a look at the JavaDoc...

particularly the section on the add() method.


public boolean add(E e)

ClassCastException - if the specified object cannot be compared with the elements currently in this set


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Seetharaman Venkatasamy
Ranch Hand

Joined: Jan 28, 2008
Posts: 5575

i.e, Test2 must implements either Comparable or Comparator
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

TreeSet class is a sorted collections, so there should be a way to sort the object, which you want to store, so you must implements Comparable{compareTo()} or Comparator{i]Compare()[/i]} and override those methods accordin to your own sorting order.

|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Deepak Bala

Joined: Feb 24, 2006
Posts: 6662

Go through the javadoc for TreeSet to understand its behavior.

SCJP 6 articles - SCJP 5/6 mock exams - More SCJP Mocks
I agree. Here's the link:
subject: Treeset
jQuery in Action, 3rd edition