Java: Copy array of non-primitive type

arrays, copy, java

Solution

The old school way was:

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.

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)

and

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.

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.

Problem

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

Original source