JAVA中的對象復制有兩種方法,分別是深拷貝和淺拷貝。
淺拷貝是指將原始對象的引用傳遞給拷貝對象,兩個對象共享同一塊內存空間,因此改變其中一個對象的屬性值,另一個對象的屬性值也會發生改變。
深拷貝是指將原始對象完整復制一份到新的內存空間中,拷貝對象與原始對象彼此獨立,因此彼此的屬性值改變互不影響。
// 淺拷貝代碼示例 public class Person implements Cloneable { private String name; private int age; private Listhobbies; @Override public Object clone() { try { return super.clone(); } catch(CloneNotSupportedException e) { return null; } } } Person p1 = new Person(); p1.setName("小明"); p1.setAge(18); List hobbies1 = new ArrayList (); hobbies1.add("籃球"); hobbies1.add("足球"); p1.setHobbies(hobbies1); Person p2 = (Person)p1.clone(); System.out.println(p1.getHobbies() == p2.getHobbies()); // true,即兩個對象共享同一塊內存空間
// 深拷貝代碼示例 public class Person implements Serializable { private String name; private int age; private Listhobbies; public Person deepClone() throws IOException,ClassNotFoundException{ ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(this); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bis); return (Person) ois.readObject(); } } Person p1 = new Person(); p1.setName("小明"); p1.setAge(18); List hobbies1 = new ArrayList (); hobbies1.add("籃球"); hobbies1.add("足球"); p1.setHobbies(hobbies1); Person p2 = p1.deepClone(); System.out.println(p1.getHobbies() == p2.getHobbies()); // false,即兩個對象不共享同一塊內存空間