Bloch 中的 toArray
方法同时使用 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;
}
如何比较这两种复制方法,以及何时应该使用哪种方法?