views:

798

answers:

2

I am creating some doubly linked list of type Double and no matter how I declare another linked list of the same type, it always refers to the first list.

Such as:

LinkedList<LinkedList<Double>> trainingData = new LinkedList<LinkedList<Double>>();
LinkedList<LinkedList<Double>> newData = new LinkedList<LinkedList<Double>>();

Add some things to trainingData...

newData = trainingData;

Then whatever changes I make to trainingData after this assignment gets changed in newData. I've also tried passing trainingData in the constructor of newData and using a nested loop to assign trainingData's data to newData, but it is still giving me the same results where newData references trainingData.

+7  A: 

You need to iterate inside your list(s) and copy/clone each element into the new list(s).

The problem you are facing is that the LinkedList only keeps internal references to the elements that it contains. When you copy the list a to list b, what you are really doing is copying the references inside list a to list b, so any change on the original list is reflected to the newly copied list.

JPCosta
This is right. newData = trainingData causes newData and trainingData to hold a reference to the same list (the one initially assigned to trainingData). It does /not/ cause a new list copy (or new list elements) to be allocated.
Matthew Flaschen
Also note that manual iteration is really necessary because calling clone() on a linkedList instance is not enough, since it only makes a shallow copy: http://java.sun.com/javase/6/docs/api/java/util/LinkedList.html#clone()
Stephan202
@Stephen202: It may or may not be enough, depending on the contents of the list; if they are immutable objects then a shallow copy is not only fine, but preferred, since cloning immutables is a waste of CPU and memory.
Software Monkey
In his example he's using Doubles, which are immutable, so cloning them is unnecessary. Even when working with mutable objects there are times when a shallow copy is what you want. (In fact, if you find yourself doing lots of deep copies it probably makes sense to think about whether there's something wrong with your overall design.)
Laurence Gonsalves
+1  A: 

This just copies the reference to the list, not its contents.

newData = trainingData;

What you appear to need is a deep copy, something like

newData = new LinkedList();
for(LinkedList ll: trainingData)
  newData.add(ll.clone());
Peter Lawrey