import java.util.Arrays;
/**
* @author h0st:
* @version :2019年10月18日 上午9:59:36
* 数组复制的几种方式
* 1.for循环复制
* 2.clone方法复制
* 3.Arrays.copyOf
* 4.Arrays.copyOfRange
*/
public class CopyArray {
//1.for循环复制
public static void forCopy(int[] arr){
int[] arr1=new int[arr.length];
for(int i=0;i<arr.length;i++){
arr1[i]=arr[i];
}
for(int i=0;i<arr.length;i++){
System.out.print( arr1[i]+" ");
}
System.out.println();
}
public static void main(String[] args) {
int[] arr = new int[] { 34, 5, 22, -98, 6, -76, 0, -3 };
forCopy(arr);
//2.clone方法复制
int[] arr1=arr.clone();
for(int i=0;i<arr.length;i++){
System.out.print(arr1[i]+" ");
}
System.out.println();
//3.Array.copyOf(原数组,拷贝个数)
int[] arr2=Arrays.copyOf(arr, arr.length);
for(int i=0;i<arr.length;i++){
System.out.print(arr2[i]+" ");
}
System.out.println();
//4.Arrays.copyOfRange(原数组,开始位置,拷贝个数)
int[] arr3=Arrays.copyOfRange(arr, 0,arr.length);
for(int i=0;i<arr.length;i++){
System.out.print(arr3[i]+" ");
}
}
}
34 5 22 -98 6 -76 0 -3
34 5 22 -98 6 -76 0 -3
34 5 22 -98 6 -76 0 -3
34 5 22 -98 6 -76 0 -3
复制数组的四种方式
最新推荐文章于 2024-05-02 05:45:00 发布