Reputation: 9357
Why do I get original data changed in the calling method, even if copying the original List using the following in the called method :
originalDatesSerie = datesSerie ;
instead of using :
originalDatesSerie.addAll(datesSerie) ;
The original List is kept as it in the calling method when using addAll
in the called method, so result is as expected in that case.
Here is the piece of the ugly code which is Ok (but NOK if using a direct equal assignment) :
private static HashMap<String, Object> autoScaling(List<Date[]> datesSerie, List<double[]> valuesSerie,
HashMap<String, Long> xminMax) {
// Copy original List (required to keep them unchanged)
List<Date[]> originalDatesSerie = new ArrayList<Date[]> ();
originalDatesSerie.addAll(datesSerie);//do NOT use "="
List<double[]> originalValuesSerie = new ArrayList<double[]> ();
originalValuesSerie.addAll(valuesSerie);//do NOT use "="
...
// Concat new datas with original datas
originalDatesSerie.addAll(Xaxis);
originalValuesSerie.addAll(Yaxis);
}
Upvotes: 0
Views: 84
Reputation: 11185
Why do I get original data changed in the calling method, even if copying the original List using the following in the called method :
It does not matter what sort of copying you use - addAll() or '='. Your item elements are Dates which are mutable objects. Mutable objects whose references exist on two different lists can be mutated from either list. Pass immutable objects between the functions to isolate them.
Upvotes: 0
Reputation: 5824
In your first example (originalDatesSerie = datesSerie ;
) you are assigning a reference to dateSerie
to originalDatesSerie
, meaning that both are referencing the same ArrayList
. When you make a change to an object through one reference or add/delete objects, it is reflected in both.
In the second example originalDatesSerie.addAll(datesSerie) ;
, originalDatesSerie
references each of the objects in dateSerie
, but the references are a separate set of references (ListArray
). When you add objects to originalDatesSerie
, you are adding them to a separate collection.
Upvotes: 1