Java:复制非原始类型的数组

2022-01-20 00:00:00 复制 arrays java

在 Java 中复制非原始类型数组的首选方法是什么?性能问题呢?

What is the prefered way to copy an array of a non-primitve type in Java? How about performance issues?

推荐答案

老派的做法是:

public static void java.lang.System.arraycopy(Object src, int srcPos, 
         Object dest, int destPos, int length)

这会从一个现有数组复制到另一个数组.您必须自己分配新数组...假设您正在制作一个数组的副本.

This copys from one existing array to another. You have to allocate the new array yourself ... assuming that you are making a copy of an array.

从 JDK 6 开始,java.util.Arrays 类有许多 copyOf 方法用于制作具有新大小的数组副本.相关的是:

From JDK 6 onwards, the java.util.Arrays class has a number of copyOf methods for making copies of arrays, with a new size. The ones that are relevant are:

public static <T> T[] copyOf(T[] original, int newLength)

public static <T,U> T[] copyOf(U[] original, int newLength,
         Class<? extends T[]> newType)

第一个使用原始数组类型进行复制,第二个使用不同的数组类型进行复制.

This first one makes a copy using the original array type, and the second one makes a copy with a different array type.

请注意,arraycopy 和 3 参数 copyOf 都必须根据目标数组类型检查原始(源)数组中每个元素的类型.所以两者都可以抛出类型异常.2 参数 copyOf (至少在理论上)不需要进行任何类型检查,因此应该(理论上)更快.在实践中,相对性能将取决于实现.例如,arraycopy 经常被 JVM 给予特殊处理.

Note that both arraycopy and the 3 argument copyOf have to check the types of each of the elements in the original (source) array against the target array type. So both can throw type exceptions. The 2 argument copyOf (in theory at least) does not need to do any type checking and therefore should be (in theory) faster. In practice the relative performance will be implementation dependent. For instance, arraycopy is often given special treatment by the JVM.

相关文章