Android Question Is this a bug or...?

kostefar

Active Member
Licensed User
Longtime User
I´ve made a simplified version of a problem I struggled with for hours. I´m pretty sure that in an earlier version of b4a, this worked fine.

B4X:
Dim l As List
Dim m As Map
l.Initialize
m.Initialize
m.Put ("1",2)
l.Add (m)
Log (l)
m.Put ("1",1)
Log (l)


The expected result is that the only item in the list remains the same, since only once in the code is a value being added to it. However, when the content of the map that is previously added to the list, the item in the list is also changing.

B4X:
(ArrayList) [{1=2}]
(ArrayList) [{1=1}]

I tried with an Int instead of a map, and here the value remains the same = succesful.
I could just do m.initialize before the new value is replacing the old one in the map, but in the app I´m working on, there are multiple values in the map which I don´t want to be reset.
I then tried creating another map to which the change is made, that copies the first map (m2=m) but still the list seems to have a need to stay in sync with the map change.
My solution was to create a new map, and then manually copy each element of the first map to it, m2.put("1",m.get("1") etc. which seems pretty clumsy to me.
But perhaps there´s a good explanation to this, and something I can learn from.

Thanks in advance!
 

fixit30

Active Member
Licensed User
Longtime User
Map keys must be unique, therefore the second m.Put will overwrite the first entry.
 
Upvote 0

Emme Developer

Well-Known Member
Licensed User
Longtime User
As write by fixit30:
upload_2017-5-2_23-17-14.png
 
Upvote 0

JordiCP

Expert
Licensed User
Longtime User
The explanation is that non-primitive objects are passed by reference, not copied. So any changes made to m after adding it to l will also be visible from there.

The workaround you describe is the way to go if you want a "snapshot" of the map at a given moment
 
Upvote 0

kostefar

Active Member
Licensed User
Longtime User
The explanation is that non-primitive objects are passed by reference, not copied. So any changes made to m after adding it to l will also be visible from there.

The workaround you describe is the way to go if you want a "snapshot" of the map at a given moment

Thanks JordiCP, that made it all more clear. I wonder why I have not struggled more with that then, but now that I know perhaps I can use it in a creative way at some point :)
 
Upvote 0
Top