Is there a way to copy LinkedList twice in Java without reference?

I am creating some double 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.

For instance:

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

      

Add some stuff to learningData ...

newData = trainingData;  

      

Then any changes I make for training, after this assignment is changed to newData. I've also tried passing trainingData in the newData constructor and using a nested loop to assign trainingData data to newData, but it still gives me the same results that newData is referencing trainingData.

+1


a source to share


2 answers


You need to iterate through your list (s) and copy / clone each item into a new list.



The problem you are having is that the LinkedList only maintains internal references to the elements it contains. When you copy list a to list b, what you are really doing is copying the links inside list a to list b, so any changes to the original list are reflected in the newly copied list.

+7


a source


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

newData = trainingData;

      



What you need is a deep copy, something like

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

      

+1


a source







All Articles