ArrayList
中的 toArray
方法,Bloch 使用 System.arraycopy
和 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;
}
我如何比较这两种复制方法以及何时应该使用哪种方法?
最佳答案
不同的是,Arrays.copyOf
不仅复制元素,还创建一个新数组。 System.arraycopy
复制到现有数组中。
这是 Arrays.copyOf
的源代码,您可以看到它在内部使用 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;
}
关于java - : System. arraycopy 或 Arrays.copyOf 哪个更有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2589741/