简体   繁体   English

如何将 ArrayList 转换为 Array

[英]How to convert ArrayList to Array

I have a Person class我有一个Person

 public class Person 
        {
          private int age;
          private String first;
          private boolean valid;
        }

I have created an ArrayList of Person objects我创建了一个Person对象的ArrayList

ArrayList<Person> valid = new ArrayList<Person>();
        for(Person p : in)
        {
         valid.add(p);
        }

Now I want to convert this ArrayList to an array;现在我想把这个ArrayList转换成一个数组; 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[].您不能将 Object[] 转换为 Person[]。 The toArray method needs to return the right type. toArray 方法需要返回正确的类型。 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[]) 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.正如您在 Javadocs 中看到的, List.toArray()返回一个Object[] ,因此列表的通用类型信息丢失了。 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).如果您需要保留通用信息,则必须使用替代的toArray()方法,该方法采用所需类型的数组(例如,因为您可能想要将List<String>转换为List<CharSequence>等在)。

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).然而,这有点浪费,因为它强制toArray()方法在运行时构造一个适当大小的新数组(通过反射)。 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()]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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