我注意到当我第一次拥有
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/