Java – way to copy a doubly LinkedList in Java without reference

copyjavalinked-list

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.

Best Solution

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.