浅拷贝
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值指向同一块内存地址。
@Dataclass Student implements Cloneable {private String name;private int age;@Overrideprotected Student clone() throws CloneNotSupportedException {return (Student) super.clone();}}
public class ShallowCopy {public static void main(String[] args) throws CloneNotSupportedException {Student s = new Student();s.setAge(12);s.setName("yinglv");Student s2 = s.clone();System.out.println(s==s2);//falseSystem.out.println(s2.getName() == s.getName());//true}}
深拷贝
深拷贝跟浅拷贝不同的一点在于,新对象的属性指向不同的地址空间,深拷贝可以通过序列化的方式实现。
public Student cloneObject() throws IOException, ClassNotFoundException {ByteArrayOutputStream outputStream = new ByteArrayOutputStream();ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);objectOutputStream.writeObject(this);ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);return (Student) objectInputStream.readObject();}
