clone():ArrayList.clone()我以为是浅拷贝 [英] clone(): ArrayList.clone() I thought does a shallow copy

查看:187
本文介绍了clone():ArrayList.clone()我以为是浅拷贝的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

ArrayList<Integer> a=new ArrayList<Integer>();
a.add(5);
ArrayList<Integer> b=(ArrayList<Integer>)a.clone();
a.add(6);
System.out.println(b.toString());

在上面这段代码中,我认为 clone()做一个浅拷贝。因此, b a 应该指向相同的内存位置。但是,当我执行 b.toString()时,答案只是 5 。如果 clone()执行浅拷贝,为什么 6 也不会显示?

In the above piece of code, i think clone() does a shallow copy. So, b and a should point to the same memory location. However, when i do b.toString(), the answer is only 5. Why is 6 also not displayed if clone() does a shallow copy?

推荐答案

浅拷贝并不意味着它们指向相同的内存位置。这只是一项任务:列表b = a;

Shallow copy does not mean that they point to the same memory location. That would be just an assignment:List b = a;.

克隆会创建一个新的实例,并保存相同的元素。这意味着您有2个不同的列表,但它们的内容是相同的。如果更改第一个列表中对象的状态,它将在第二个列表中更改。 (因为你使用的是不可变类型 - Integer - 你无法观察到这一点)

Cloning creates a new instance, holding the same elements. This means you have 2 different lists, but their contents are the same. If you change the state of an object inside the first list, it will change in the second list. (Since you are using an immutable type - Integer - you can't observe this)

但是,你应该考虑不使用 clone()。它适用于集合,但通常它被认为是破碎的。使用copy-constructors - new ArrayList(originalList)

However, you should consider not using clone(). It works fine with collections, but generally it's considered broken. Use the copy-constructors - new ArrayList(originalList)

这篇关于clone():ArrayList.clone()我以为是浅拷贝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆