ArrayList的深拷贝与浅拷贝

1、深拷贝

通过以下代码进行理解

java 复制代码
import java.util.ArrayList;
import java.util.List;
 
public class Demo {
    public static void main(String[] args) {
        List<Integer> c = new ArrayList<>();
        c.add(1);
        c.add(2);
        c.add(3);
 
        List<Integer> c1 = new ArrayList<>(c);//深拷贝
        System.out.println(c);
        System.out.println(c1);
    }
}

输出结果为:(c和c1输出的结果相同)

2、浅拷贝

通过以下代码进行理解

java 复制代码
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
 
public class Demo {
    public static void main(String[] args) {
        List<Integer> c = new ArrayList<>();
        c.add(1);
        c.add(2);
        c.add(3);
        c.add(4);
        c.add(5);
 
        System.out.println(c);
        List<Integer> c1 = c.subList(2,5);
        System.out.println(c1);
        List<Integer> c2 = Collections.singletonList(c1.set(2, 99));
        System.out.println(c1);
        System.out.println(c);
 
    }
}

输出结果为:

submit进行的是浅拷贝,因此c的值也会进行改变

相关推荐
数据知道6 小时前
Windows 安全基线:组策略、UAC、Defender 深度配置
windows·安全·网络安全
大模型码小白10 小时前
在 Windows 下 Codex 安装、配置与使用详细指南
java·人工智能·windows
小小龙学IT10 小时前
C++ Placement New 与显式析构:手动对象生命周期管理的艺术
c++·windows·mfc
luyun02020210 小时前
论坛里的小工具,吾爱出品
运维·服务器·windows
老王生涯12 小时前
rust开发环境配置-Windows & GNU
开发语言·windows·rust
nLif12 小时前
进程管道通讯-伪终端方式
c++·windows
CodexDave13 小时前
Python 自动化接单实战(九):Windows 免环境交付如何打包与诊断
windows·python·自动化·python自动化·pyinstaller·软件交付·windows打包
DB哥讲数据库13 小时前
【windows安装sql server教程】25步图文详解(附安装包)
windows
惠惠软件13 小时前
快速生成磁盘目录文件-双击运行a.bat ,可以看到磁盘目录下出现了 文件目录.txt-供大家学习研究参考
windows·学习·文件列表
Starmoon_dhw14 小时前
重塑你的Windows文件夹图标 Folder Theme Studio
windows