当前位置:网站首页>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》]
]
边栏推荐
- Database multi-table link query method
- Shell -- -- -- -- -- - common gadgets, sort and uniq, tr, the cut
- What is the difference between the four common resistors?
- 什么是模板引擎?常见的模板引擎有哪些?thymeleaf的常用指令介绍。
- 常见的四种电阻之间有什么不同?
- 约束性统计星号‘*’
- Play in the cloud | The ever-changing gameplay of Tianyi cloud computer
- 对程序化交易系统接口有什么误区?
- 测试工程师,看不上年薪20w,原因居然是...
- shell之函数和数组
猜你喜欢
随机推荐
数组学习笔记
【磁场建模项目2020-02-Lilin】采集板硬件规范
[MySql]实现多表查询-一对一,一对多
经典面试题 之 JVM调优
MySql中什么是索引?常用的索引有哪些种类?索引在什么情况下会失效?
是什么推动了量化交易接口的发展?
MySQL学习笔记
常见的数学物理方程
DBCO-PEG-DSPE,磷脂-聚乙二醇-二苯并环辛炔,在无铜离子的催化下反应
职业量化交易员对量化交易有什么看法?
如何灵活运用量化交易接口的优势取长补短?
如何通过股票量化交易接口实现盈利稳定?
百度地图——鹰眼轨迹服务
OpenSSF's open source software risk assessment tool: Scorecards
浅谈ArraryList的浅克隆和深克隆
常微分方程的幂级数解法
[MySql] implement multi-table query - one-to-one, one-to-many
Seize the opportunity of quantitative trading fund products, and quantitative investment has room for development?
如何通过通达信量化交易接口达到长期的收益?
如何让你的量化交易系统具有概率优势,具有正向收益预期呢?