Meaningless Drivel is fun!
The moose likes Beginning Java and the fly likes ClassCastException on list.toArray()? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "ClassCastException on list.toArray()?" Watch "ClassCastException on list.toArray()?" New topic

ClassCastException on list.toArray()?

Alok Pota
Ranch Hand

Joined: Mar 07, 2001
Posts: 185
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

Joined: Feb 22, 2001
Posts: 104
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();

Campbell Hore

Joined: Mar 15, 2001
Posts: 7
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).
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.
I agree. Here's the link:
subject: ClassCastException on list.toArray()?
It's not a secret anymore!