• 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Bear Bibeault
  • Devaka Cooray
  • Liutauras Vilda
  • Jeanne Boyarsky
Sheriffs:
  • Knute Snortum
  • Junilu Lacar
  • paul wheaton
Saloon Keepers:
  • Ganesh Patekar
  • Frits Walraven
  • Tim Moores
  • Ron McLeod
  • Carey Brown
Bartenders:
  • Stephan van Hulst
  • salvin francis
  • Tim Holloway

getting Class cast exception  RSS feed

 
Ranch Hand
Posts: 299
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator




I get a class cast excpetion at line Integer []arr=(Integer[])arr. Acc to my understanding, arr is of type Object, and i try to downcast it to Integer[]. But why does it throw Class Cast Exception
 
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


i believe you meant




and the answer to your question is simple. in your code you have this HashSet wich add a series of Integer but the hasset it self just contains a bunch of Objects.

Second you instanciate a List named list with the previos set collections and called to the method toArray() wich always return Object[] then you try to cast but you can't beause the Object[] Array has nothing to do with the Integer[] array is just like saying Animal[] cast to Integer[] they have nothing.

 
Maan Suraj
Ranch Hand
Posts: 299
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Jose, but i dont understand one thing....

Second you instanciate a List named list with the previos set collections and called to the method toArray() wich always return Object[] then you try to cast but you can't beause the Object[] Array has nothing to do with the Integer[] array is just like saying Animal[] cast to Integer[] they have nothing.




As far as I Understand, Object is the SuperClass/ Parent Class for all objects. Interger[] is a subclass for Object[] , so i thought downcasting is possible and should not throw any error(Unlike the case of Animal[] and Integer[] you are talking about). Could you please explain this?
 
Jose Ayerdis
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
let me put it clear you are kind of doing this

Here you can se it clearly that you cannot cast an object to an integer array



Because after all thats what you retrieve from your HashSet
 
Maan Suraj
Ranch Hand
Posts: 299
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok.. Thanks Jose... Got it .....:-)
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!