Java: Copy array of non-primitive type

坚强是说给别人听的谎言 提交于 2019-12-09 16:03:49

问题


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


回答1:


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.




回答2:


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();


来源:https://stackoverflow.com/questions/1366303/java-copy-array-of-non-primitive-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!