8

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

1
  • Do you only want to copy the array itself (i.e. the references in the array), or do you also want to clone all the objects that the references in the array point to? Commented Sep 2, 2009 at 7:47

2 Answers 2

14
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();
Sign up to request clarification or add additional context in comments.

2 Comments

Touché oxbow - someone came along half an hour later with the same answer and was accepted!
@pjp: I accepted the answer of Stephen as he additionally addressed the performance part of the question.
7

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.

1 Comment

For whoever wondered int[] array = {1, 2, 3}; int[] copy = Arrays.copyOf(array, array.length, Integer.class); won't compile ("The method copyOf(int[], int) in the type Arrays is not applicable for the arguments (int[], int, Class<Integer>)")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.