This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes ClassCastException Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "ClassCastException" Watch "ClassCastException" New topic
Author

ClassCastException

jose chiramal
Ranch Hand

Joined: Feb 12, 2010
Posts: 266
Why do I get this exception :

public static void main (String args[])
{
Set st2 = (Set) new TreeSet();
st2.add(new Integer(1));
}

java.lang.ClassCastException
at Basic.TreeSet.main(TreeSet.java)
Exception in thread "main"
Ernest Friedman-Hill
author and iconoclast
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

From the stack trace, I see that this method is in a class called "TreeSet". So in main(), you're constructing an instance of this containing class, not the java.util.TreeSet you were expecting. Since Basic.TreeSet doesn't implement Set, boom. A ClassCastException.

It's always a bad idea to name a class after a class that appears in the core Java APIs!


[Jess in Action][AskingGoodQuestions]
Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3419
    
  12
It appears that code is in a file called TreeSet.java, so presumably it contains a TreeSet class. Does that class implement the Set interface ? If not, the you can't cast it to a Set (and if it did then you wouldn't need to cast it).


Joanne
Xiong Neng
Greenhorn

Joined: Mar 03, 2009
Posts: 1
I suppose the TreeSet is not the java.util.TreeSet.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37945
    
  22
Xiong Neng, welcome to JavaRanch
 
Consider Paul's rocket mass heater.
 
subject: ClassCastException
 
Similar Threads
Stack
How about with java.util.Stack??
Stack referencing stack
Stack referencing other stack
resultset problem