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

相关推荐
呉師傅4 分钟前
东芝3525AC彩色复印机CC219测试页打印方法【实际操作】
运维·网络·windows·计算机外设·电脑
开开心心就好1 小时前
音频编辑工具,多端支持基础剪辑易操作
java·网络·windows·java-ee·电脑·maven·excel
季布,3 小时前
本地Windows测试:钉钉群消息/文件传输到Python服务(完整教程)
windows·python·钉钉
iAkuya4 小时前
(leetcode)力扣100 46二叉树展开为链表(递归||迭代||右子树的前置节点)
windows·leetcode·链表
海天鹰5 小时前
文件右键菜单删除转换为pdf格式
windows
WXDcsdn5 小时前
Windows无法使用Microsoft to PDF输出PDF文件
windows·pdf·电脑·it运维
百事牛科技6 小时前
WinRAR整理密码功能详解:告别反复输密码
windows·winrar
玖釉-6 小时前
[Vulkan 学习之路] 26 - 图像视图与采样器 (Image View and Sampler)
c++·windows·图形渲染
weixin_419658316 小时前
UISpy:Windows 界面控件的“显微镜“[特殊字符]
windows·python·测试工具·ui
光芒Shine7 小时前
【WSL-操作指南】
windows