0

why does variants2 changes after any change happening in variants? does this have something to do with passing variables as a reference? how does it work?

Map<String, double> variants = {"value1": 1.0, "value2": 2.0, "value3": 3.0};
Map<String, double> variants2 = variants;
variants2["value1"] = 500.0;
print(variants);

console prints --> {value1: 500.0, value2: 2.0, value3: 3.0}

at the same time this code below works with no problems, why? what's the difference?

double var1 = 5.5;
double var2 = var1;
var2 = 500.0;
print(var1);

console prints --> 5.5

  • 1
    I think this has been answered https://stackoverflow.com/a/25171102/4917965 – Nico Spencer Oct 18 '21 at 15:55
  • and also read this one https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value/40523#40523 – Jahidul Islam Oct 18 '21 at 16:15
  • `variants2 = variants` makes `variants2` refer to the same object as `variants`. It does not create a new copy. If you want a copy, you can do: `var variants2 = {...variants};`. In the second code example "works with no problems" because `var2 = 500.0` makes `var2` refer to a different object; it does not mutate the original object. – jamesdlin Oct 18 '21 at 18:26
  • works perfectly, thank you – Ahmed Abd El-Moez Oct 19 '21 at 15:39

0 Answers0