简体   繁体   中英

How to convert ArrayList to Array

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;

你必须做这样的事情

Person[] people = valid.toArray(new Person[valid.size()]);

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[])

你可以尝试这样的事情:

Person[] people = valid.toArray(new Person[valid.size()]);

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, eg:

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()]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM