首页 技术 正文
技术 2022年11月15日
0 收藏 817 点赞 2,799 浏览 1076 个字

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内容的一个完善,Java基础(十三)–深拷贝和浅拷贝

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,104
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,580
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,428
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,200
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,835
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,918