为什么我的链接列表在克隆后似乎指向相同的东西?
我注意到,当我第一次拥有时
list2 = (LinkedList)list.clone();
,我可以独立地操作两个列表,例如。 list2.remove(1)
但后来当我
list = (LinkedList)list2.clone();
这样做时 list.remove(1)
list2 也会受到影响。这是为什么?
更新
示例输入:
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()
会进行浅拷贝。但为什么第一次就成功了呢?
I noticed that when I first have
list2 = (LinkedList)list.clone();
I could operate on both lists independently eg. list2.remove(1)
But later when I do
list = (LinkedList)list2.clone();
when I do list.remove(1)
list2 is affected too. Why is that?
UPDATE
My code http://pastie.org/2598096
Example input:
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.
I think its because super.clone()
makes a shallow copy. But why then did it work the 1st time?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
一般来说,您应该编写自己的
clone()
函数来实现您想要的深复制。因为java不保证这一点。以下是维基百科的引用:
我认为这个< /a> 也值得一读。
In general you should write your own
clone()
function to achieve the deep copy you want. because java is not guaranteeing this.Here is a quote from wikipedia:
And I think this is also worth reading.
这使得:
这表明
正在按预期工作。
that makes:
that demonstrates
is working as expected.
不,不是。你的观察在这里是错误的。
No it isn't. Your observations are at fault here.
这也是可能发生的情况。
基本上,列表可能不保存实际的对象数据,而是对它们的引用。换句话说,它跟踪这些对象的指针(也称为内存地址)。
在英语中,这就像说“这些房子位于这些地址”,并且您将地址列表存储在电话簿中。 clone() 可能不会复制房子,但它可能会复制电话簿
还有可能有人存储“电话簿存储在 B 架上”,将其写下来,然后递给其他人一张纸,上面写着“电话簿存放在 B 架上”
Here's also what might be happening.
Basically, the list is probably not holding the actual object data, but references to them. In other words, it's keeping track of the pointers (a.k.a. memory addresses) to those objects.
In English, this is like saying "These houses are at these addresses", and you are storing the list of addresses in a phone book. The clone() might not be copying the house, but it might be copying the phone book
There's also the chance that someone might be storing "The phone book is stored on shelf B", writing it down, and handing someone else a paper saying that "The phone book is stored on shelf B"