ArrayList of objects to array of object, does not work

Hello,

I have a short problem in transforming an ArrayList full of User 's to an array full of User 's.

It seems Java isn't supporting this directly, example code:

function User[] getUsers()

{

...

ArrayList<User> userArrayList =new ArrayList<User>;

...

//fill list with User 's

...

User[] users = (User[]) userArrayList.toArray();

return users;

}

This code gives a class cast exception, cannot cast Object[] to User[].

Why is this?

When you manually iterate the arrayList and cast all objects to the User type in the array it will work, but it is more code + kinda takes out the use for a toArray() function.

Is there something I am doing wrong or is it just not possible in java?

[949 byte] By [radicjesa] at [2007-11-27 2:27:36]
# 1

try this

function User[] getUsers()

{

...

ArrayList<User> userArrayList = new ArrayList<User>;

...

//fill list with User 's

...

User[] users = userArrayList.toArray(new User[0]);

return users;

}

georgemca at 2007-7-12 2:38:30 > top of Java-index,Java Essentials,Java Programming...
# 2
Thank you very much, that works like a charm.Any idea why you have to do this though ?I checked the javadoc but it does not specify anything about it
radicjesa at 2007-7-12 2:38:30 > top of Java-index,Java Essentials,Java Programming...
# 3

If you have a Collection<T> after erasure the type of T is Object. Another reason you can't do it is that you could create arrays of generic types, which is not supported.

p.s. if the array you pass in as a parameter to toArray is big enough it will be used otherwise a new array of the same runtime type is allocated.

YoGeea at 2007-7-12 2:38:30 > top of Java-index,Java Essentials,Java Programming...