Search code examples
javaclone

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 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?


Solution

  • 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.