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.
a source to share
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.
a source to share