java之浅拷贝、深拷贝
1、java数据类型
java数据类型分为基本数据类型和引用数据类型
基本数据类型:byte、short、int、long、float、double、boolean、char。
引用类型:常见的有类、接口、数组、枚举等。
2、浅拷贝、深拷贝
以下探讨的浅拷贝、深拷贝是通过Object类中的clone()方法进行的。
Object.javaprotected native Object clone() throws CloneNotSupportedException;
2.1 浅拷贝:引用数据类型只复制引用。
Book.java
public class Book {private String bookName;private int price;getter/settertoString();
}
Persion.java
public class PeoSon implements Cloneable {private int age;private Book book;public PeoSon(int age) {this.age = age;}@Overrideprotected Object clone() throws CloneNotSupportedException {return super.clone();}getter/setter
toString();
}
测试:
Book book = new Book("编译原理", 10);PeoSon p1 = new PeoSon(123);p1.setBook(book);PeoSon p2 = (PeoSon) p1.clone();System.out.println(p1);System.out.println(p2);System.out.println("--------p1更改book的name值后--------");p1.getBook().setBookName("java从入门到入坟"); System.out.println(p1);System.out.println(p2);
打印结果:
PeoSon{age=123, book=Book{bookName=‘编译原理’, price=10}}
PeoSon{age=123, book=Book{bookName=‘编译原理’, price=10}}
--------p1更改book的name值后--------
PeoSon{age=123, book=Book{bookName=‘java从入门到入坟’, price=10}}
PeoSon{age=123, book=Book{bookName=‘java从入门到入坟’, price=10}}
可以看到,只修改了p1中引用对象book的名称,但是p2中引用对象book的名称也发生了变化!
原因: PeoSon p2 = (PeoSon) p1.clone() 是浅拷贝,p1、p2指向同一块堆内存空间。
修改图书名称后:
上述类PeoSon 类实现Cloneable 接口;使用clone()方法时,必须实现该接口并且复写clone()方法。
public interface Cloneable {
}
Cloneable 只是一个标记性接口,实现这个接口表明要重写clone()。
并且在Object类的clone()方法中也明确说明了:
if the class of this object does not implement the interface Cloneable , then a
CloneNotSupportedException is thrown.
/*** Creates and returns a copy of this object. The precise meaning* of "copy" may depend on the class of the object. The general* intent is that, for any object {@code x}, the expression:* <blockquote>* <pre>* x.clone() != x</pre></blockquote>* will be true, and that the expression:* <blockquote>* <pre>* x.clone().getClass() == x.getClass()</pre></blockquote>* will be {@code true}, but these are not absolute requirements.* While it is typically the case that:* <blockquote>* <pre>* x.clone().equals(x)</pre></blockquote>* will be {@code true}, this is not an absolute requirement.* <p>* By convention, the returned object should be obtained by calling* {@code super.clone}. If a class and all of its superclasses (except* {@code Object}) obey this convention, it will be the case that* {@code x.clone().getClass() == x.getClass()}.* <p>* By convention, the object returned by this method should be independent* of this object (which is being cloned). To achieve this independence,* it may be necessary to modify one or more fields of the object returned* by {@code super.clone} before returning it. Typically, this means* copying any mutable objects that comprise the internal "deep structure"* of the object being cloned and replacing the references to these* objects with references to the copies. If a class contains only* primitive fields or references to immutable objects, then it is usually* the case that no fields in the object returned by {@code super.clone}* need to be modified.* <p>* The method {@code clone} for class {@code Object} performs a* specific cloning operation. First, if the class of this object does* not implement the interface {@code Cloneable}, then a* {@code CloneNotSupportedException} is thrown. Note that all arrays* are considered to implement the interface {@code Cloneable} and that* the return type of the {@code clone} method of an array type {@code T[]}* is {@code T[]} where T is any reference or primitive type.* Otherwise, this method creates a new instance of the class of this* object and initializes all its fields with exactly the contents of* the corresponding fields of this object, as if by assignment; the* contents of the fields are not themselves cloned. Thus, this method* performs a "shallow copy" of this object, not a "deep copy" operation.* <p>* The class {@code Object} does not itself implement the interface* {@code Cloneable}, so calling the {@code clone} method on an object* whose class is {@code Object} will result in throwing an* exception at run time.** @return a clone of this instance.* @throws CloneNotSupportedException if the object's class does not* support the {@code Cloneable} interface. Subclasses* that override the {@code clone} method can also* throw this exception to indicate that an instance cannot* be cloned.* @see java.lang.Cloneable*/protected native Object clone() throws CloneNotSupportedException;
2.2 深拷贝
Book.java
public class Book implements Cloneable{private String bookName;private int price;@Overrideprotected Object clone() throws CloneNotSupportedException {return super.clone();}public Book(String bookName, int price) {this.bookName = bookName;this.price = price;}
get/set
toString();
}
Person.java
public class PeoSon implements Cloneable {private int age;private Book book;public PeoSon(int age) {this.age = age;}@Overrideprotected Object clone() throws CloneNotSupportedException {PeoSon p = (PeoSon) super.clone();Book clone = (Book) book.clone();p.setBook(clone);return p;}get/set
toString();
}
注意:Book.java、Person.java 都实现了Cloneable接口并且复写了clone()方法。
测试:
Book book = new Book("编译原理", 10);PeoSon p1 = new PeoSon(123);p1.setBook(book);PeoSon p2 = (PeoSon) p1.clone();System.out.println(p1);System.out.println(p2);System.out.println("-----p1更改book的name值后-----");p1.getBook().setBookName("java从入门到入坟");System.out.println(p1);System.out.println(p2);
PeoSon{age=123, book=Book{bookName=‘编译原理’, price=10}}
PeoSon{age=123, book=Book{bookName=‘编译原理’, price=10}}
-----p1更改book的name值后-----
PeoSon{age=123, book=Book{bookName=‘java从入门到入坟’, price=10}}
PeoSon{age=123, book=Book{bookName=‘编译原理’, price=10}}
可以看到修改p1中引用数据类型book的bookName属性值后,p2对应属性值不会发生改变。
原因:深拷贝会把所有属性值复制一份,因此改变一个对象的属性值后,其他对象不受影响。
在深度拷贝中,需要被拷贝的对象中的所有引用数据类型都实现Cloneable()接口并且重写clone()方法,如果一个对象有好多引用数据类型,则比较费劲,有没有其他方法呢 ? 使用序列化!
序列化是将对象写到流中便于传输,而反序列化则是把对象从流中读取出来。这里写到流中的对象则是原始对象的一个拷贝,因为原始对象还存在 JVM 中,所以我们可以利用对象的序列化产生克隆对象,然后通过反序列化获取这个对象。
注意每个需要序列化的类都要实现 Serializable 接口,如果有某个属性不需要序列化,可以将其声明为 transient,即将其排除在克隆属性之外。
public Object deepClone() throws Exception {// 序列化ByteArrayOutputStream bos = new ByteArrayOutputStream();ObjectOutputStream oos = new ObjectOutputStream(bos);oos.writeObject(this);// 反序列化ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());ObjectInputStream ois = new ObjectInputStream(bis);return ois.readObject();}
简单使用案例:
public class CC2 implements Serializable {private String color;@Overridepublic String toString() {return "CC2{" +"color='" + color + '\'' +'}';}public CC2(String color) {this.color = color;}public String getColor() {return color;}public void setColor(String color) {this.color = color;}
}
public class BB2 implements Serializable {private String name;private int age;private CC2 c;public BB2() {}public BB2(String name, int age, CC2 c) {this.name = name;this.age = age;this.c = c;}@Overridepublic String toString() {return "BB2{" +"name='" + name + '\'' +", age=" + age +", c=" + c +'}';}public String getName() {return name;}public void setName(String name) {this.name = name;}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public CC2 getC() {return c;}public void setC(CC2 c) {this.c = c;}
}
public class AA2 implements Serializable {private int age;private BB2 b;public AA2(int age, BB2 b) {this.age = age;this.b = b;}@Overridepublic String toString() {return "AA2{" +"age=" + age +", b=" + b +'}';}public Object deepClone() throws Exception {// 序列化ByteArrayOutputStream bos = new ByteArrayOutputStream();ObjectOutputStream oos = new ObjectOutputStream(bos);oos.writeObject(this);// 反序列化ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());ObjectInputStream ois = new ObjectInputStream(bis);return ois.readObject();}public int getAge() {return age;}public void setAge(int age) {this.age = age;}public BB2 getB() {return b;}public void setB(BB2 b) {this.b = b;}
}
public class TT2 {public static void main(String[] args) throws Exception {AA2 aa2 = new AA2(10, new BB2("李四", 20, new CC2("红色")));AA2 o = (AA2) aa2.deepClone();System.out.println(aa2);System.out.println(o);System.out.println("----------------------------------");aa2.getB().setName("新的值");System.out.println(aa2);System.out.println(o);}
}
参考链接