tags:

views:

753

answers:

2

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

+8  A: 
System.arraycopy

(which gives you the ability to copy arbitrary portions of an array via the offset and length parameters). Or

java.util.Arrays.copyOf

Which was added in JDK 6 and is a generic method so it can be used:

Integer[] is = new Integer[] { 4, 6 }
Integer[] copy = Arrays.copyOf(is, is.length);

Or it can narrow a type:

Number[] is = new Number[]{4, 5};
Integer[] copy = Arrays.copyOf(is, is.length, Integer[].class);

Note that you can also use the clone method on an array:

Number[] other = is.clone();
oxbow_lakes
Touché oxbow - someone came along half an hour later with the same answer and was accepted!
pjp
@pjp: I accepted the answer of Stephen as he additionally addressed the performance part of the question.
desolat
It's no problem at all *desolat* - not sure why *pjp* is so touchy!
oxbow_lakes
+3  A: 

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.

Stephen C