当前位置:网站首页>Talking about Shallow Cloning and Deep Cloning of ArraryList
Talking about Shallow Cloning and Deep Cloning of ArraryList
2022-08-09 16:13:00 【Brother doesn't want to work hard】
关于ArraryList的克隆,可以分为浅克隆和深克隆,也称为浅复制和深复制.
一、浅克隆
浅克隆,将目标ArraryListThe reference to each element object points to原始ArraryListThe memory address of the corresponding element object in the stack space.
Just copied the originalArrayListA reference to the element object in ,目标ArrayList和原始ArrayListIt's a win-win situation,Not in the real sense“新的ArrayList”.
简单来说,Either change the originalArrayListThe element object in the ,Or change the targetArrayList中的元素对象,Just a shallow clone,所有的 目标ArraryList 和 原始ArraryList It will also change together
The most common ways to apply shallow cloning
1. list.addAll()
将原始ArrayListThe whole is added to the targetArrayList中
(1)使用 addAll(Collection<? extends E> c) 的语法,是将原始ArrayListOverall added targetArrayList的尾部.
例如:desList.addAll(srcList)
(2)使用 addAll(int index, Collection<? extends E> c) 的语法,其中index用于指定 collection The index of where the first element of is inserted.简单来说,就是将原始ArrayListOverall added targetArrayList的指定index下标位置.
例如:desList.addAll(2, srcList)
public static void main(String[] args) {
//原始List
List<SmsCoupon> srcList = new ArrayList<>();
Book item1 = new Book();
item1.setId("1");
item1.setName("《JavaZero basics from entry to collapse》");
srcList.add(item1);
Book item2 = new Book();
item2.setId("2");
item2.setName("《10年JavaDaniel's bald experience》");
srcList.add(item2);
//目标List
List<SmsCoupon> desList = new ArrayList<>();
//1.将原始List添加到目标List尾部
desList.addAll(srcList);
System.out.println(desList);
//2.将原始List添加到目标List指定索引位置(索引下标为2的位置)
desList.addAll(2, srcList);
}// 输出结果
[
Book [id=1, name=《JavaZero basics from entry to collapse》],
Book [id=2, name=《10年JavaDaniel's bald experience》]
]
参考 addAll() 的源码,如下图所示
不难看出,addAll() Just as a whole instance,把原始Listloop into targetList中.
所以说,Even if you create a new target yourselfArrayList,The constant will be originalArrayListThe loop is added to the targetArrayList,Also just fill in the reference,The original reference type is not changed.
/**
* addAll() 源码
*/
public boolean addAll(Collection<? extends E> c) {
Object[] a = c.toArray();
int numNew = a.length;
ensureCapacityInternal(size + numNew); // Increments modCount
System.arraycopy(a, 0, elementData, size, numNew);
size += numNew;
return numNew != 0;
}2. list.clone()
Also the same will be originalArrayListThe whole is added to the targetArrayList中
public static void main(String[] args) {
//原始List
ArrayList<Book> srcList = new ArrayList<>();
Book item1 = new Book();
item1.setId("1");
item1.setName("《JavaZero basics from entry to collapse》");
srcList.add(item1);
Book item2 = new Book();
item2.setId("2");
item2.setName("《10年JavaDaniel's bald experience》");
srcList.add(item2);
//目标List
ArrayList<Book> desList = (ArrayList<Book>)srcList.clone();
System.out.println(desList);
}// 输出结果
[
Book [id=1, name=《JavaZero basics from entry to collapse》],
Book [id=2, name=《10年JavaDaniel's bald experience》]
]
参考 clone() 的源码,如下图所示
返回的是新的ArrayList元素对象,但是存储数据的elementData,The stored object still points to the originalArrayListThe stored element object.
简单来说,ArrayListThis class implements deep cloning,But the way the element object is actually stored is still the same浅克隆
当然,If you have to thinkclone()实现深克隆,Then it has to be rewrittenclone的方式实现,
Personally, I prefer to write a method myself as a tool method to directly call the implementation
/**
* clone() 源码
*/
public Object clone() {
try {
@SuppressWarnings("unchecked")
ArrayList<E> v = (ArrayList<E>) super.clone();
v.elementData = Arrays.copyOf(elementData, size);
v.modCount = 0;
return v;
} catch (CloneNotSupportedException e) {
// this shouldn't happen, since we are Cloneable
throw new InternalError();
}
}二、深克隆
深克隆,将原始ArraryList中的元素对象,Reallocate space in heap memory,Store these element objects as new element objects.
Deep clone out the targetArraryList 与 原始ArraryList They do not affect each other during operation
A method of deep cloning is listed below,Can be cited as a tool
/**
* Arrary的深度Copy
* @param srcList 原始list
* @return 目标list
* @throws IOException
* @throws ClassNotFoundException
*/
public List<Book> ArraryListDepthCopy(List<Book> srcList) throws IOException, ClassNotFoundException {
//序列化
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(srcList);
//反序列化
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
ObjectInputStream ois = new ObjectInputStream(bais);
List<Book> desList = (List<Book>) ois.readObject();
return desList;
}测试结果
public static void main(String[] args) {
//原始List
List<Book> srcList = new ArrayList<>();
Book item1 = new Book();
item1.setId("1");
item1.setName("《JavaZero basics from entry to collapse》");
srcList.add(item1);
Book item2 = new Book();
item2.setId("2");
item2.setName("《10年JavaDaniel's bald experience》");
srcList.add(item2);
//目标List
List<Book> desList = new ArrayList<>();
try {
desList = ArraryListDepthCopy(srcList);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// 输出结果
System.out.println(desList);
}// 输出结果
[
Book [id=1, name=《JavaZero basics from entry to collapse》],
Book [id=2, name=《10年JavaDaniel's bald experience》]
]
边栏推荐
猜你喜欢

【胡扯】量子力学与单线程

如何设计一个高并发系统?

多线程学习

xshell7连接工具下载

docker安装单机版redis、集群版redis

Shell编程之循环语句

DBCO-PEG-DSPE, Phospholipid-Polyethylene Glycol-Dibenzocyclooctyne, Reaction Without Copper Ion Catalysis

百度地图——地图找房功能

navicat for Oraclel链接oracle 报错oracle library is not loaded的解决办法

DSPE-PEG-Hydrazide,DSPE-PEG-HZ,磷脂-聚乙二醇-酰肼MW:1000
随机推荐
基于FPGA的FIR滤波器的实现(3)—采用Filter Design & Analysis设计
WebShell简介
量化程序化交易如何去使用以及执行?
[MySql]实现多表查询-一对一,一对多
FilenameFilter filters filenames
Shell functions and arrays
FilenameFilter过滤文件名
软件工程基础知识--软件过程模型
leetcode_jz
C语言——函数、参数和指针
股票程序化交易如何理解自己的交易系统?
相似图像的检测方法
MySQL principle and optimization: Limit the query optimization
docker安装seata(指定配置文件、数据库、容器数据卷等)
测试工程师,看不上年薪20w,原因居然是...
方法学习笔记
对于程序化交易,重在预测还是重在对策呢?
道路形态(道路要素)
百度地图——鹰眼轨迹服务
985测试工程师被吊打,学历和经验到底谁更重要?