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的值也会进行改变

相关推荐
大龄门外汉35 分钟前
CPP学习之list使用及模拟实现
windows·学习·list
joe023511 小时前
电脑安装 Win10 提示无法在当前分区上安装Windows的解决办法
windows·gpt·电脑·uefi
前端 贾公子12 小时前
vue-cli 模式下安装 uni-ui
前端·javascript·windows
Elastic 中国社区官方博客13 小时前
在 Windows 上使用 Docker 运行 Elastic Open Crawler
大数据·windows·爬虫·elasticsearch·搜索引擎·docker·容器
CIAS16 小时前
clonezilla 导出自动化恢复iso
linux·windows·clonezilla
墨菲安全17 小时前
Node.js Windows下路径遍历漏洞
windows·node.js·路径遍历漏洞
NoirSeeker17 小时前
在windows平台上基于OpenHarmony sdk编译三方库并暴露给ArkTS使用(详细)
c++·windows·arkts·鸿蒙·交叉编译
红藕香残玉簟秋18 小时前
【python学习】windows使用conda管理python虚拟环境
windows·python·conda
紫云无堤1 天前
20250717 Ubuntu 挂载远程 Windows 服务器上的硬盘
服务器·windows·ubuntu
wydxry1 天前
断网情况下,网线直连 Windows 笔记本 和Ubuntu 服务器
服务器·windows·ubuntu