Shallow Copy Deep Copy Cloneable
Shallow Copy Deep Copy Cloneable 浅拷贝深拷贝克隆 浅拷贝只拷贝当前对象不拷贝引用不改变引用值 深拷贝即拷贝当前对象又拷贝引用改变引用值类似递归层层拷贝package further.zwf.cloneable; /** * 用户类主类 * * author ZengWenFeng * date 2023.11.17 * mobile 13805029595 * email 117791303QQ.com */ public class User implements Cloneable { String name; // 基本类型包装类 UserAddress address; // 引用类型成员 public User(String name, UserAddress address) { this.name name; this.address address; } // ----------------------- // 1. 默认浅拷贝只克隆当前对象不克隆引用对象 // ----------------------- protected User clone() throws CloneNotSupportedException { return (User) super.clone(); } // ----------------------- // 2. 深拷贝连引用对象一起克隆 // ----------------------- protected User deepClone() throws CloneNotSupportedException { // 先克隆自身 User cloneUser (User) super.clone(); // 重点把引用类型 address 也克隆一份 cloneUser.address this.address.clone(); return cloneUser; } }package further.zwf.cloneable; /** * 地址类引用类型 * * author ZengWenFeng * date 2023.11.17 * mobile 13805029595 * email 117791303QQ.com */ public class UserAddress implements Cloneable { String city; // 城市 public UserAddress(String city) { this.city city; } // 重写clone() —— 用于深拷贝 protected UserAddress clone() throws CloneNotSupportedException { return (UserAddress) super.clone(); } }package further.zwf.cloneable; /** * 测试类 * * author ZengWenFeng * date 2023.11.17 * mobile 13805029595 * email 117791303QQ.com */ public class UserCopyTest { public static void main(String[] args) throws CloneNotSupportedException { // 1. 创建原始对象 UserAddress address new UserAddress(北京); User user new User(张三, address); System.out.println( 浅拷贝测试 ); // 2. 浅拷贝 User shallowCopyUser user.clone(); // 修改拷贝对象的地址 shallowCopyUser.address.city 上海; // 原对象也被改了 System.out.println(原对象地址 user.address.city); // 上海 System.out.println(浅拷贝对象地址 shallowCopyUser.address.city); // 上海 System.out.println(\n 深拷贝测试 ); // 3. 深拷贝 UserAddress address2 new UserAddress(北京); User user2 new User(李四, address2); User deepCopyUser user2.deepClone(); // 修改深拷贝对象的地址 deepCopyUser.address.city 广州; // 原对象 完全不受影响 System.out.println(原对象地址 user2.address.city); // 北京 System.out.println(深拷贝对象地址 deepCopyUser.address.city); // 广州 } }