浅拷贝

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.

Object类的clone方法将基于该类的对象创建一个新的实例,并且使用该对象中的所有字段初始化新实例中的字段,就像赋值操作样;字段的内容本身不会被克隆。
以下面这段代码举例,首先实例化了一个对象s,然后使用使用该对象克隆出一个新的对象s2,s和s2是两个不同的对象,但是对象中的字段是通过赋值实现的,这样的话就意味着对象s和对象s2中的name值指向同一块内存地址。

  1. @Data
  2. class Student implements Cloneable {
  3. private String name;
  4. private int age;
  5. @Override
  6. protected Student clone() throws CloneNotSupportedException {
  7. return (Student) super.clone();
  8. }
  9. }
  1. public class ShallowCopy {
  2. public static void main(String[] args) throws CloneNotSupportedException {
  3. Student s = new Student();
  4. s.setAge(12);
  5. s.setName("yinglv");
  6. Student s2 = s.clone();
  7. System.out.println(s==s2);//false
  8. System.out.println(s2.getName() == s.getName());//true
  9. }
  10. }

深拷贝

深拷贝跟浅拷贝不同的一点在于,新对象的属性指向不同的地址空间,深拷贝可以通过序列化的方式实现。

  1. public Student cloneObject() throws IOException, ClassNotFoundException {
  2. ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
  3. ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
  4. objectOutputStream.writeObject(this);
  5. ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
  6. ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
  7. return (Student) objectInputStream.readObject();
  8. }

参考文献

[1]https://www.cnblogs.com/qlwang/p/7889802.html