Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Copy array of non-primitive type

Tags:

java

arrays

copy

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

like image 277
desolat Avatar asked Sep 02 '09 07:09

desolat


1 Answers

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();
like image 81
oxbow_lakes Avatar answered Nov 13 '22 04:11

oxbow_lakes