list 转化 为数组 一般调用toArray方法,
List<String> list = new ArrayList<>();
list.add("aaa");
list.add("bbb");
String[] array = (String[]) list.toArray();
这样调用会报异常:
java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;
正确的调用如下:
List<String> list = new ArrayList<>();
list.add("aaa");
list.add("bbb");
String[] array = list.toArray(new String[list.size()]);
jdk8 中源码如下:
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;
}