Clone在Java中就是用来复制对象,通过分配一个和源对象相同大小的内存空间,然后创建一个新的对象,那么他和=的区别在哪?
通过=实现对象拷贝:
@Data @NoArgsConstructor @AllArgsConstructor @ToString public class Student implements Cloneable{ private int id; private String name; private int sex; @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } }
public static void main(String[] args) { Student student = new Student(1001, "sam", 1); Student student1 = student; System.out.println(student == student1); student1.setName("zhangsan"); System.out.println(student.toString()); }
结果:
true Student(id=1001, name=zhangsan, sex=1)
从结果上看,student和student1指向同一个对象,我修改了student1的数据,由于student指向同一个对象,导致student的数据也变了,但是
现在,我想要源对象的副本,不希望源对象和target对象之间有任何关联,我们可以使用clone()
clone()实现对象拷贝:
public static void main(String[] args) throws Exception{ Student student = new Student(1001, "sam", 1); Student student1 = (Student)student.clone(); System.out.println(student == student1); student1.setName("zhangsan"); System.out.println(student.toString()); }
结果:
false Student(id=1001, name=sam, sex=1)
从结果上看,我们知道这次通过clone()创建了一个对象,和源对象没有关联
PS:克隆一个对象并不会调用对象的构造方法
做个预告,下篇文章会写深拷贝和浅拷贝,包括clone内容的一个完善