什么更有效:System.arraycopy vs Arrays.copyOf? [英] What is more efficient: System.arraycopy vs Arrays.copyOf?
本文介绍了什么更有效:System.arraycopy vs Arrays.copyOf?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
ArrayList中的toArray方法,Bloch使用System.arraycopy和Arrays.copyOf来复制数组。
The toArray method in ArrayList , Bloch uses both System.arraycopy and Arrays.copyOf to copy an array .
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;
}
如何比较这两种复制方法,何时使用哪种?
How to compare these two copy methods , when to use which?
推荐答案
区别在于 Arrays.copyOf
不仅复制元素,它还创建一个新数组。 System.arrayCopy
复制到现有数组中。
The difference is that Arrays.copyOf
does not only copy elements, it also creates a new array. System.arrayCopy
copies into an existing array.
以下是数组的来源。 copyOf
,你可以看到它在内部使用 System.arraycopy
来填充新数组。
Here is the source for Arrays.copyOf
, as you can see it uses System.arraycopy
internally to fill up the new array.
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;
}
这篇关于什么更有效:System.arraycopy vs Arrays.copyOf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文