引用类型的深复制
浅复制的两种方式
1.通过Cloneable接口实现 代码实例:
package com.entity;
import lombok.Data;
/**
* @Author:
* @Date: 2021/11/14/10:22
* @Description:
**/
@Data
public class Player implements Cloneable {
private String name;
private String age;
private Team team;
@Override
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
package com.entity;
import lombok.Data;
/**
* @Author:
* @Date: 2021/11/14/10:23
* @Description:
**/
@Data
public class Team {
private String name;
private String org;
}
@Test
public void test1(){
Team team = new Team();
team.setName("湖人");
team.setOrg("NBA");
Player player = new Player();
player.setName("科比");
player.setAge("41");
player.setTeam(team);
System.out.println(player);
try {
Player player1 =(Player) player.clone();
player1.setName("pl kobe");
player1.setAge("42");
Team team1 = player1.getTeam();
System.out.println(team1);
team1.setName("China");
team1.setOrg("world");
player1.setTeam(team1);
System.out.println("复制后的:player =" +player );
System.out.println("复制后的:player1 =" +player1 );
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
2.通过拷贝构造函数实现
package com.entity;
import lombok.Data;
/**
* @Author:
* @Date: 2021/11/14/13:45
* @Description:
**/
@Data
public class Age {
private int age;
public Age(int age) {
this.age = age;
}
}
package com.entity;
import lombok.Data;
/**
* @Author:
* @Date: 2021/11/14/13:43
* @Description:
**/
@Data
public class Coach {
private String name;
private Age age;
public Coach(Coach p) {
this.name=p.name;
this.age=p.age;
}
public Coach(Age age,String name) {
this.age=age;
this.name=name;
}
}
@Test
public void test2(){
Age a = new Age(60);
Coach coach1 = new Coach(a,"杨学增");
Coach coach2 = new Coach(coach1);
System.out.println("coach1是:" + coach1);
System.out.println("coach2是:" + coach2);
coach1.setName("王菲");
a.setAge(57);
System.out.println("coach1修改后是:" + coach1);
System.out.println("coach2修改后是:" + coach2);
}
可见类型位Age类型的内容会随着修改其中的一个对象的修改而修改,那么浅拷贝会进行引用传递,也就是只是将该成员变量的引用值(内存地址)复制一份给新的对象。因为实际上两个对象的该成员变量都指向同一个实例
String类型修改不会影另一个对象