java中数组的复制方式
1、五种方式
- for循环、
- clone方法、
- System.arraycopy方法、
- Arrays.copyOf方法、
- Arrays.copyOfRange方法。
2、示例
2.1、for循环
//源数组
int[] source = {10,30,20,40};
//目标数组
int[] target = new int[source.length];
for (int i = 0;i < source.length;i++){
target[i] = source[i];
}
2.2、System.arraycopy()
public class ArrayCopyDemo{
public static void main(String[] args){
int[] a = {1,2,3,4};
int[] b ={8,7,6,5,4,3,2,1};
int[] c = {10,20};
try{
System.arraycopy(a, 0, b, 0, a.length);
// 下面语句发生异常,目标数组c容纳不下原数组a的元素
System.arraycopy(a, 0, c, 0, a.length);
}catch(ArrayIndexOutOfBoundsException e){
System.out.println(e);
}
for(int elem: b){
System.out.print(elem+" ");
}
}
}
2.3、Arrays.copyOf()、Arrays.copyOfRange()
Arrays.copyOf()
Arrays.copyOfRange()
// Arrays.copyOf()
int[] arr2 = new int[10000];
arr2 = Arrays.copyOf(arr, 10000);
// Arrays.copyOfRange()
int[] arr4 = new int[10000];
arr4 = Arrays.copyOfRange(arr, 0, 10000);
2.4、clone
public static void main(String[] args) {
int[] arr3 = new int[10000];
arr3 = arr.clone();
}