對于Java中對象的拷貝,有兩種方式:淺拷貝和深拷貝。
淺拷貝是指創建一個新對象,并將原來對象的所有屬性值復制到新對象中,如果屬性值為引用類型,則新對象和原來對象共享該引用類型對象。即修改新對象的引用類型屬性,會影響原對象。
public class ShallowCopyDemo { public static void main(String[] args) throws CloneNotSupportedException { Person person1 = new Person("Tom", 22, new Address("Beijing")); Person person2 = (Person) person1.clone(); //淺拷貝 System.out.println("person1: " + person1); System.out.println("person2: " + person2); System.out.println(person1.getAddress() == person2.getAddress()); //true,共享Address對象 person2.getAddress().setCity("Shanghai"); System.out.println("person1: " + person1); System.out.println("person2: " + person2); } } class Person implements Cloneable { private String name; private int age; private Address address; //構造方法、get、set方法省略 @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } } class Address { private String city; //構造方法、get、set方法省略 }
深拷貝是指創建一個新對象,并將原來對象的所有屬性值復制到新對象中,對于屬性值為引用類型的屬性,則新對象會獨立創建該引用類型的對象。即修改新對象的引用類型屬性,不會影響原對象。
public class DeepCopyDemo { public static void main(String[] args) throws Exception { Person person1 = new Person("Tom", 22, new Address("Beijing")); Person person2 = person1.deepCopy(); //深拷貝 System.out.println("person1: " + person1); System.out.println("person2: " + person2); System.out.println(person1.getAddress() == person2.getAddress()); //false,不共享Address對象 person2.getAddress().setCity("Shanghai"); System.out.println("person1: " + person1); System.out.println("person2: " + person2); } } class Person { private String name; private int age; private Address address; //構造方法、get、set方法省略 public Person deepCopy() throws Exception { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos); oos.writeObject(this); //序列化 ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bais); return (Person) ois.readObject(); //反序列化 } } class Address implements Serializable { private String city; //構造方法、get、set方法省略 }
上一篇java 對象頭和反射
下一篇vue的濾鏡功能