Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

ClassCastException

 
Ranch Hand
Posts: 266
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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"
 
author and iconoclast
Posts: 24207
46
Mac OS X Eclipse IDE Chrome
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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!
 
Rancher
Posts: 3742
16
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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).
 
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I suppose the TreeSet is not the java.util.TreeSet.
 
Marshal
Posts: 80296
434
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Xiong Neng, welcome to JavaRanch
 
Consider Paul's rocket mass heater.
reply
    Bookmark Topic Watch Topic
  • New Topic