当前位置: 首页 > news >正文

java八股文面试[java基础]——浅拷贝和深拷贝

 

自验证:创建Class Student两个类, Student中含有Class对象

public class Class implements Cloneable {public String getName() {return name;}public void setName(String name) {this.name = name;}private String name;public Class(String name) {this.name = name;}@Overrideprotected Object clone() throws CloneNotSupportedException {return super.clone();}
}
public class Student implements Cloneable {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 Class getClazz() {return clazz;}public void setClazz(Class clazz) {this.clazz = clazz;}private String name;private int age;private Class clazz;public Student(String name, int age, Class clazz) {this.name = name;this.age = age;this.clazz = clazz;}@Overrideprotected Object clone() throws CloneNotSupportedException {return super.clone();}
}

测试代码:

public class Copy {public static void main(String[] args) throws CloneNotSupportedException {Class clazz = new Class("一班");Student student = new Student("张三", 18, clazz);Student newStudent = (Student) student.clone();student.getClazz().setName("二班");System.out.println("=== student===");System.out.println(student);System.out.println(student.getName());System.out.println(student.getAge());System.out.println(student.getClazz());System.out.println(student.getClazz().getName());System.out.println("=== newStudent===");System.out.println(newStudent);System.out.println(newStudent.getName());System.out.println(newStudent.getAge());System.out.println(newStudent.getClazz());System.out.println(newStudent.getClazz().getName());}
}

输出:

可以看到不同的Student对象,但是有相同的Class对象

修改Student clone方法:

@Overrideprotected Object clone() throws CloneNotSupportedException {Student student = (Student) super.clone();student.setClazz((Class) clazz.clone());return student;}

可以看到不同的class对象,不同的值:

知识来源:

【23版面试突击】什么是浅拷贝和深拷贝_哔哩哔哩_bilibili

强引用、弱引用介绍:

https://www.cnblogs.com/Scott007/archive/2013/05/15/3080739.html

http://www.lryc.cn/news/136932.html

相关文章:

  • 【DC-DC的原理图及Layout设计要点】
  • TCP可靠性机制
  • solidity0.8.0的应用案例13:数字签名及应用:NFT白名单
  • 视频集中存储/直播点播平台EasyDSS内核无法启动是什么原因?
  • 【网络】DNS | ICMP | NAT | 代理服务器
  • 详细手机代理IP配置
  • 【C++】—— 简述C++11新特性
  • 协议的分层结构
  • Linux下彻底卸载jenkins
  • Nebula基础的查询操作介绍
  • C++ STL序列式容器(详解)
  • C++获取map最小值算法,STL---std::min_element()!
  • 如何在Java实现TCP方式发送和接收Socket消息(多线程模式)
  • SYBASE查询全量字段及对应的表名方法
  • Alions 8.6 下 Redis 7.2.0 集群搭建和配置
  • Android Retrofit 使用及原理详解~
  • 三种主要的云交付服务和安全模型
  • python爬虫实战(3)--爬取某乎热搜
  • IPv4,IPv6,TCP,路由
  • Java 计算文本相似度
  • MySQL 视图
  • 深入理解回调函数qsort:从入门到模拟实现
  • 【Git基础】获取远程仓库
  • chatGPT界面
  • windows一键启动jupyter
  • 树形结构的快速生成
  • Android笔记(二十七):自定义Dialog实现居中Toast
  • css实现文字的渐变,适合大屏
  • 软考高级系统架构设计师系列论文八十七:论企业应用集成
  • C++设计模式之适配器模式