Reputation: 973
A Dart question: In the following, to show (in my mind) "normal behaviour", the value of the key-value pair is not changed without explicitly setting it:
Map<String,String> mup = {};
mup['a']='fred';
var val = mup['a'];// val==fred
val = 'joe';
print(mup); // (a: fred} - unchanged
mup['a']=val; //set
print(mup); // (a: joe} - changed OK
A strange way to show it, but nothing surprising there. But if the value is a list, if the list value is changed, the map is updated immediately:
Map<String,List> mup = {};
mup['a']=[1,2,3,4,5,6];
var val = mup['a'];
val[1]=66;
print (mup);//{a: [1, 66, 3, 4, 5, 6]}
So mup has changed without explicitly changing it! What is going on...please?
Surprising to me, but I am a beginner!
Steve
Upvotes: 2
Views: 351
Reputation: 657496
var val = mup['a']
returns a reference to the list [1,2,3,4,5,6]
not a copy.
If you modify it this is also reflected in the list inside the map which is in fact the same list.
Basically you can imagine it as looking at the same thing in a box but from two different holes.
Upvotes: 2