浅拷贝
假设现在有A ,将A拷贝的B中,A和B此时指向同一快地址空间,改变其中一个值,另一个的值也会随之改变,这就叫浅拷贝。
Test
创建一个Test类,实现了两个接口,其中一个接口是Comparable(主要用作排序),另一个接口时Cloneable。这里我们主要讨论Cloneable接口。
实现Cloneable接口后需要重写Clone的方法。如下代码所示
import java.util.Objects;
public class Test implements Comparable<Test>,Cloneable {
private String name;
private int age;
public Test(String name, int age){
this.name = name;
this.age = age;
this.m = new Money();
}
@Override
public String toString() {
return "Test{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public int compareTo(Test o) {
return this.age-o.age;
}
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
Main
要进行异常CloneNotSupportedException处理
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws CloneNotSupportedException {
Test[] tests = new Test[3];
tests[0] = new Test("zhangsan" , 12);
tests[1] = new Test("lisi" , 15);
tests[2] = new Test("wangwu" , 10);
Arrays.sort(tests); //排序
System.out.println(Arrays.toString(tests));
System.out.println("=======");
Test test = new Test("zhangsan" , 12);
Test test1 = (Test) test.clone();
System.out.println(test);
System.out.println(test1);
}
}
运行结果
如图,是浅拷贝地址指向。
深拷贝
假设现在有A ,将A拷贝的B中,A和B此时指向不同地址空间,改变其中一个值,不会影响另一个值的改变,这就叫深拷贝。
如下代码,需要实现对money=19.9d的深拷贝。在浅拷贝的基础上进行代码的些许修改。
Money
public class Money implements Cloneable {
public double money = 19.9;
@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
Test
对重写后的==clone()==方法进行改变。
tmp只是一个临时变量。
import java.util.Objects;
public class Test implements Cloneable {
private String name;
private int age;
public Money m;
public Test(String name, int age){
this.name = name;
this.age = age;
this.m = new Money();
}
@Override
protected Object clone() throws CloneNotSupportedException {
//return super.clone();
Test tmp = (Test) super.clone();//修饰符是protected不同包之间要使用super
tmp.m = (Money) this.m.clone();//test谁调用this指向谁
return tmp;
}
}
Main
import java.util.Arrays;
public class Main {
public static void main(String[] args) throws CloneNotSupportedException {
Test test = new Test("zhangsan" , 12);
Test test1 = (Test) test.clone();
System.out.println("======");
System.out.println(test.m.money);
System.out.println(test1.m.money);
test1.m.money = 99.99;
System.out.println(test.m.money);
System.out.println(test1.m.money);
}
}
运行结果
深拷贝是对对象的对象进行了拷贝。拷贝处理两份new.
tmp充当零时变量,这里暂未画出。