哪个更有效:System.arraycopy 还是 Arrays.copyOf? [英] What is more efficient: System.arraycopy or Arrays.copyOf?

查看:31
本文介绍了哪个更有效:System.arraycopy 还是 Arrays.copyOf?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ArrayList 中的toArray 方法,Bloch 使用System.arraycopyArrays.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆