开发者社区 问答 正文

什么是更有效的:System.arraycopy或Arrays.copyOf?

Bloch中的toArray方法ArrayList同时使用System.arraycopy和Arrays.copyOf复制一个数组。

public 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; } 如何比较这两种复制方法,何时应使用哪种复制方法? 问题来源于stack overflow

展开
收起
保持可爱mmm 2020-02-08 20:27:38 625 分享 版权
1 条回答
写回答
取消 提交回答
  • 不同之处在于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; }

    2020-02-08 20:27:46
    赞同 展开评论
问答地址: