ArrayList.toArray()方法最后实现是下面的代码
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
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;
}
public static native void arraycopy
effective java 2 th p 107上提到list.toArray()方法是内部锁定,是线程安全的
而 System.arraycopy是本地方法
为什么说上面的方法是线程安全的,没有看到内部锁定
public static <T,U> T[] copyOf(U[] original, int newLength, Class<? extends T[]> newType) {
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;
}
public static native void arraycopy
effective java 2 th p 107上提到list.toArray()方法是内部锁定,是线程安全的
而 System.arraycopy是本地方法
为什么说上面的方法是线程安全的,没有看到内部锁定
如果返回值不是一个新的数组,而与collection 内部可能的数组是同一个,那么collection 有可能修改数组,你的程序也可能对返回的数组进行修改,这样就不安全了