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);
}
In your first example (
originalDatesSerie = datesSerie ;) you are assigning a reference todateSerietooriginalDatesSerie, meaning that both are referencing the sameArrayList. 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) ;,originalDatesSeriereferences each of the objects indateSerie, but the references are a separate set of references (ListArray). When you add objects tooriginalDatesSerie, you are adding them to a separate collection.