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

相关推荐
程序视点5 小时前
Window 10文件拷贝总是卡很久?快来试试这款小工具,榨干硬盘速度!
windows
wuk9986 小时前
基于MATLAB编制的锂离子电池伪二维模型
linux·windows·github
lzb_kkk7 小时前
【C++】C++四种类型转换操作符详解
开发语言·c++·windows·1024程序员节
Paper_Love14 小时前
x86-64_windows交叉编译arm_linux程序
arm开发·windows
前端若水15 小时前
通过 Windows 共享文件夹 + 手机访问(SMB协议)如何实现
windows·智能手机
超龄超能程序猿1 天前
dnSpy 使用教程
windows·microsoft
路来了1 天前
Python小工具之PDF合并
开发语言·windows·python
csdn_aspnet1 天前
在 Windows 上安装和运行 Apache Kafka
windows·kafka
江山如画,佳人北望1 天前
C#程序入门
开发语言·windows·c#
AustinCyy1 天前
【环境配置】Neo4j Community Windows 安装教程
windows·neo4j