当前位置:网站首页>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》]
]
边栏推荐
猜你喜欢
随机推荐
redis6在centos7的安装
OpenCV - 矩阵操作 Part 3
MongoDB adds permission management
【磁场建模项目2020-02-Lilin】采集板硬件规范
百度开源e-chart初探
Shell编程之正则表达式
运算符学习
【OpenGL】三、OpenGL总结:OpenGL坐标系
[MySql]实现多表查询-一对一,一对多
Mathematica 数据分析(简明)
浅谈一下量化交易与程序化交易
Shell -- -- -- -- -- - common gadgets, sort and uniq, tr, the cut
Play in the cloud | The ever-changing gameplay of Tianyi cloud computer
JS——循环结构经典例题解析与分享
如何通过股票量化交易接口实现盈利稳定?
基于FPGA的FIR滤波器的实现(2)—采用kaiserord & fir2 & firpm函数设计
思维导图FreeMind安装问题及简单使用
OpenCV - 图像模板匹配 matchTemplate
防汛添利器,数字技术筑起抗洪“大堤”
docker安装seata(指定配置文件、数据库、容器数据卷等)









