java - 为什么我的链接列表在克隆后似乎指向相同的东西?

标签 java clone

我注意到当我第一次拥有

list2 = (LinkedList)list.clone();

我可以独立地对两个列表进行操作,例如。 list2.remove(1)

但稍后我会这样做

list = (LinkedList)list2.clone();

当我执行 list.remove(1) 时,list2 也会受到影响。这是为什么?

更新

我的代码 http://pastie.org/2598096

示例输入:

4 8
1 5 2 3
4
I 1 2
R 2
C 1 10
I 4 2

> javac Main.java && java Main < ./input/betterlist0.in 
[ 1, 5, 2, 3, ] -- [ 2, 1, 5, 2, 3, ] // list2 can be modified from list1 independently
YES9 8
[ 2, 5, 2, 3, ] -- [ 2, 5, 2, 3, ] // now when list2 is modified, list1 gets modified too. 

我认为这是因为 super.clone() 进行了浅拷贝。但是为什么它第一次起作用了呢?

最佳答案

一般来说你应该自己写一个clone()函数来实现你想要的深拷贝。因为 java 不保证这一点。

这是来自 wikipedia 的引述:

The default implementation of Object.clone() performs a shallow copy. When a class desires a deep copy or some other custom behavior, they must perform that in their own clone() method after they obtain the copy from the superclass.

我认为 this也值得一读。

关于java - 为什么我的链接列表在克隆后似乎指向相同的东西?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7553478/

相关文章:

java - 找不到符号变量

git - 如何使用 GIT 从 Bitbucket 将所有存储库克隆到团队中

c++ - Qt c++ - 克隆一个对象

javascript - 有没有办法在函数内重新分配参数,并且它也会影响调用范围?

c# - instanceof/is 优先的原因

java - 如何传递字符串、日期等数据类型

java - java clone() 是如何真正使用浅拷贝的?

java - 克隆引用了java中另一个可变对象的对象

java - libGDX/roboVM : How to fix "Native Library libhfscompressor.dylib already loaded in another classloader"?

java - 用于在非分隔字符串中查找带有通配符的字符串的正则表达式