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