aspose file tools*
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
Author

Treeset

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());
System.out.println(at.first());
}
}

SCJP6.0,My blog Ranchers from Delhi
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18997
    
  40

Take a look at the JavaDoc...

http://java.sun.com/javase/6/docs/api/java/util/TreeSet.html

particularly the section on the add() method.


add

public boolean add(E e)

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


Henry


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
Bartender

Joined: Feb 24, 2006
Posts: 6662
    
    5

Go through the javadoc for TreeSet to understand its behavior.


SCJP 6 articles - SCJP 5/6 mock exams - More SCJP Mocks
 
 
subject: Treeset