错误写法
ArrayList<Integer> list = new ArrayList();
list.add(1);
list.add(2);
Integer[] array = (Integer[]) list.toArray();
编译的时候不出现问题,但是运行时会出现ClassCastException。
参考阿里巴巴开发手册
源码参考
public <T> T[] toArray(T[] a) {
if (a.length < size)
// Make a new array of a's runtime type, but my contents:
return (T[]) Arrays.copyOf(elementData, size, a.getClass());
System.arraycopy(elementData, 0, a, 0, size);
if (a.length > size)
a[size] = null;
return a;
}