Java的拷贝先可以分为两种:
1.引用拷贝,顾名思义就是拷贝了对象的一份引用出来
举例如下:
引用拷贝是牵一发而动全身的
2.对象拷贝
深拷贝、浅拷贝都是对象拷贝,也就是说深拷贝和浅拷贝都拷贝了原对象,那么二者的差别在哪呢?
深浅的差别在于如果我们的对象中有指向其他对象的引用,浅拷贝只会拷贝引用,而深拷贝不仅会拷贝引用,还有引用所指向的对象
浅拷贝演示:
class People implements Cloneable{
int age;
String name;
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void eat() {
System.out.println("恰饭");
}
int[] arr = {1, 2, 3, 4, 5, 6};
public People( ) {
}
public People(int a) {
System.out.println(a);
}
public People clone() throws CloneNotSupportedException {
People people;
people = (People) super.clone();
//people.arr = Arrays.copyOf(people.arr,people.arr.length);
return people;
}
}
public static void main(String[] args) {
People people1 = new People();
people1.setAge(1800);
people1.setName("张大炮");
People people2 = null;
//people1.setAge(18);
try {
people2 = people1.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
System.out.println("people1 和people2 的引用一样吗?");
System.out.println(people1 == people2);
System.out.println("people1 和people2 的对象一样吗?");
System.out.println(people1.equals(people2));
System.out.println("people1中的数组和people2中的数组的引用一样吗?");
System.out.println(people1.arr == people2.arr);
System.out.println("people1中的数组和people2中的数组的对象一样吗?");
System.out.println(people1.arr.equals(people2.arr));
System.out.println("修改people2的名字为张小跑");
people2.setName("张小跑");
System.out.println("people1 name :" + people1.getName());
System.out.println("people2 name :" + people2.getName());
people2.arr[0] = 2;
System.out.println("修改people2中数组0号元素为2");
System.out.println("people1 arr :" + Arrays.toString(people1.arr));
System.out.println("people2 arr :" + Arrays.toString(people2.arr));
System.out.println("people1中的数组和people2中的数组的引用一样吗?");
System.out.println(people1.arr == people2.arr);
System.out.println("people1中的数组和people2中的数组的对象一样吗?");
System.out.println(people1.arr.equals(people2.arr));
}
输出结果演示:
深拷贝如下:
为了实现深拷贝,拷贝方法更改如下:
public People clone() throws CloneNotSupportedException {
People people;
people = (People) super.clone();
people.arr = Arrays.copyOf(people.arr,people.arr.length);
return people;
}
执行效果如下:
深拷贝的话,如果拷贝对象中的引用中还有引用,那么引用中引用的对象也会被拷贝,顾名思义为深拷贝
需要注意的是:记得实现Cloneable接口
如果不听话,偏不实现呢?
java.lang.CloneNotSupportedException
不支持克隆异常
当没有实现Cloneable接口或者不支持克隆方法时,调用其clone()方法则抛出该异常。