Java数组复制的三种方法
将数组元素逐个复制到目标数组中
使用for循环
1 | public class ArrayCopy01 { |
复制结果
1 | [10, 20, 30, 40] |
使用System类的arraycopy()方法
arraycopy()方法
1 | public static native void arraycopy(Object src, int srcPos, Object dest, int destPos, int length) |
1 | public class ArrayCopy02 { |
复制结果
1 | java.lang.ArrayIndexOutOfBoundsException |
使用Arrays类的copyOf()方法和copyOfRange()方法
copyOf()方法
1 | public static int[] copyOf(int[] original, int newLength) { |
copyOfRange()方法
1 | public static int[] copyOfRange(int[] original, int from, int to) { |
1 | public class ArrayCopy03 { |
复制结果
1 | [10, 20, 30, 40] |