我们常用的的转换方法是
ArrayList<String> list=new ArrayList<>();
list.toArray();
list.toArray(new String[0]);
list.toArray(new String[list.size()]);
调用toArray无参方法时底层进行了:
1、里面会去调用Array.copyOff方法用,arrayList中维护的数组以及arrayList的size作为参数
public Object[] toArray() {
return Arrays.copyOf(elementData, size);
}
2、Array.copyOf调用重载方法,将以上参数以及,list中的数组的数据类型(Object)作为参数调用copyof方法
public static <T> T[] copyOf(T[] original, int newLength) {
return (T[]) copyOf(original, newLength, original.getClass());
}
3、再次调用Array.copyOf的重载方法,判断数据类型是否时Object,传入的肯定是个Object所以这里会穿件一个Object类型的数组进行返回
并低啊用System.arraycopy将list中维护的数组中的数据复制到新的数组中去
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
@SuppressWarnings("unchecked")
T[] copy = ((Object)newType == (Object)Object[].class)
? (T[]) new Object[newLength]
: (T[]) Array.newInstance(newType.getComponentType(), newLength);
System.arraycopy(original, 0, copy, 0,
Math.min(original.length, newLength));
return copy;
}
4 返回转化出来的数组数组类型是Object 且不是深拷贝
调用toArray有参方法时底层进行了
1、判断传入的数组的长度是否小于list 的size,若不小于则直接进行进行数组的复制,之后将出的部分补上null,并返回数组; 若传入数组的长度小于list 的size那么去调用Arrays.copyOf方法,将list维护的数组
list的size以及传入数组的数据类型作为参数调用Arrays.copyOf
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;
}
2调用Arrays.copyOf时会判断传入的数据类型是否时Object,若是则创建一个Object数组并调用System.arraycopy数组进行复制
若传入数据类型是其他类型则调用Array.newInstance创建一个对应数据类型的数组再调用System.arraycopy进行数组复制
注意:System.arraycopy是浅复制