What is the prefered way to copy an array of a non-primitve type in Java? How about performance issues?
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With