ArrayList.toArray() API介绍
Object[] toArray()
按适当顺序(从第一个到最后一个元素)返回包含此列表中所有元素的数组。
T[] toArray(T[] a)
按适当顺序(从第一个到最后一个元素)返回包含此列表中所有元素的数组;返回数组的运行时类型是指定数组的运行时类型。
直接构造进行数组的强制转换是不正确的。
String[] str = (String[])list1.toArray();
会爆出异常
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object;
at TestArrayList.main(TestArrayList.java:9)
改成,使用第二个接口
String[] str = (String[])list1.toArray(new String[0]);
import java.util.ArrayList;
import charactor.Hero;
public class TestCollection {
public static void main(String[] args) {
ArrayList heros = new ArrayList();
// 初始化5个对象
for (int i = 0; i < 5; i++) {
heros.add(new Hero("hero " + i));
}
Hero specialHero = new Hero("special hero");
heros.add(specialHero);
System.out.println(heros);
Hero hs[] = (Hero[])heros.toArray(new Hero[]{});
System.out.println("数组:" +hs);
}
}
需要注意的是,如果要转换为一个Hero数组,那么需要传递一个Hero数组类型的对象给toArray(),这样toArray方法才知道,你希望转换为哪种类型的数组,否则只能转换为Object数组