一、拷贝方式简单实用
1、clone()方法:
int[] arr=new int[2];
int[] arrCopy=arr.clone();
2、System.arraycopy:
参数1:原数组
参数2:原数组起始位置(从这个位置开始复制)
参数3:目标数组
参数4:目标数组粘贴原数组值的第一个位置
参数5:复制的个数
int[] arr=new int[2];
int[] arrCopy=new int[2];
System.arraycopy(arr,0,arrCopy,0,arr.length);
3、Arrays.copyOf
int[] arr=new int[2]
int[] arrCopy=Arrays.copyOf(arr, arr.length);//参数一位old数组,参数二为赋值old数组前n个元素
二、深浅拷贝
对于数组中元素分为基本数据类型和引用数据类型,对于基本数据类型都是深拷贝,也就是改变old数组,copy数组的值不会跟着改变。但是当是引用数据类型是都为浅拷贝。
public class LeetCode {
private int res=Integer.MAX_VALUE;
@Test
public void test(){
User[] users=new User[1];
users[0]=new User();
users[0].a=1;
User[] usersCopy1=new User[1];
User[] usersCopy2=new User[1];
User[] usersCopy3=new User[1];
usersCopy1=users.clone();
System.arraycopy(users,0,usersCopy2,0,users.length);
usersCopy3 = Arrays.copyOf(users, 1);
users[0].a=10;
System.out.println(usersCopy1[0].a);
System.out.println(usersCopy2[0].a);
System.out.println(usersCopy3[0].a);
}
}
class User{
public int a;
public int b;
}
运行结果如下:
可以看出old数组中元素改变,其他copy数组也跟着改变。