• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

ClassCastException on list.toArray()?

 
Alok Pota
Ranch Hand
Posts: 185
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
List list = new ArrayList();
list.add(new City());
list.add(new City());
City[] cities = (City[]) list.toArray(); <---
always gives ClassCastException. Have no idea why?
 
Siva Prasad
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alok
toArray() method from List interface always returns an Object Array.
And when you try to do downcast (cast an Object with an object derived from it) you get this ClassCastException.
So try to change the code like this and should work.
Object[] cities = list.toArray();
((City)cities[0]).myFun();

Cheers
Siva
 
Campbell Hore
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Alok,
You might want to take a look at the "Array Operations" section at the bottom of the page at the following address (part of Sun's Java Tutorial).
http://java.sun.com/docs/books/tutorial/collections/interfaces/collection.html
This section deals with exactly what I think you want to do, i.e. convert a list into an array of objects, in this case a City[].
Applying the information at the above address to your code gives:

Passing in 'new City[0]' seems slightly odd to me, but that is how it works. Perhaps someone more knowledgeable than me can shed light on the thinking behind this?
Let us know how you get on.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic