• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ClassCastException

 
jose chiramal
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 24212
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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!
 
Joanne Neal
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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).
 
Xiong Neng
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I suppose the TreeSet is not the java.util.TreeSet.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49841
70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Xiong Neng, welcome to JavaRanch
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic