什么是更有效的:System.arraycopy或Arrays.copyOf? [英] What is more efficient: System.arraycopy or Arrays.copyOf?
本文介绍了什么是更有效的:System.arraycopy或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 can I compare these two copy methods and when should I 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.
这里是Arrays.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或Arrays.copyOf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文