Forums Register Login

ClassCastException

+Pie Number of slices to send: Send
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"
+Pie Number of slices to send: Send
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!
+Pie Number of slices to send: Send
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).
+Pie Number of slices to send: Send
I suppose the TreeSet is not the java.util.TreeSet.
+Pie Number of slices to send: Send
Xiong Neng, welcome to JavaRanch
Why should I lose weight? They make bigger overalls. And they sure don't make overalls for tiny ads:
a bit of art, as a gift, the permaculture playing cards
https://gardener-gift.com


reply
reply
This thread has been viewed 1052 times.
Similar Threads
resultset problem
Stack referencing other stack
Stack
How about with java.util.Stack??
Stack referencing stack
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 19:21:47.