开发者

Why do my linked lists appear to point to same thing after 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开发者_StackOverflow 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?


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:

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.

And I think this is also worth reading.


LinkedList l1 = new LinkedList();
l1.add("A");l1.add("B");

LinkedList l2 = (LinkedList)l1.clone();
out("l2 after clone: "+l2.size());
l2.remove(0);
out("l2 after remove: "+l2.size());
l1 = (LinkedList)l2.clone();
out("l1 cloned from l2: "+l1.size());
l1.remove(0);
out("l1 after remove :"+l1.size());
out("l2 after l1's remove:"+l2.size());

that makes:

l2 after clone: 2
l2 after remove: 1
l1 cloned from l2: 1
l1 after remove :0
l2 after l1's remove:1

that demonstrates

.clone

is working as expected.


when I do list.remove(1) list2 is affected too

No it isn't. Your observations are at fault here.


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"

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜