I have a Person class
public class Person
{
private int age;
private String first;
private boolean valid;
}
I have created an ArrayList of Person objects
ArrayList<Person> valid = new ArrayList<Person>();
for(Person p : in)
{
valid.add(p);
}
Now I want to convert this ArrayList to an array; I have tried this:
Person[] people = (Person[]) valid.toArray();
but this is throwing exception
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Lcom.net.Person;
4 Answers 4
you have to do something like this
Person[] people = valid.toArray(new Person[valid.size()]);
4 Comments
toArray will allocate new array if the one you will pass is not large enught to fit all contents. What happend with accepted answer ??You can't cast an Object[] to a Person[]. The toArray method needs to return the right type. There's an overloaded version of that method which takes an array of your type.
Person[] people = valid.toArray(new Person[valid.size()]);
http://docs.oracle.com/javase/7/docs/api/java/util/Collection.html#toArray(T[])
Comments
Can you try something like this:
Person[] people = valid.toArray(new Person[valid.size()]);
Comments
As you can see in the Javadocs, List.toArray() returns an Object[], so the list's generic type information is lost. That's why your cast doesn't work.
If you need to preserve the generic information, you must use the alternative toArray() method which takes an array of the desired type (because you could, for instance, want to turn a List<String> into a List<CharSequence> and so on).
All you need to do is pass an empty array of the desired type, e.g.:
list.toArray(new Person[]{});
However this is a little wasteful, as it forces the toArray() method to construct a new array of the appropriate size at runtime (via reflection). If instead you pass in an array that is already large enough, it will reuse that array avoiding the reflection and extra allocation.
list.toArray(new Person[list.size()]);