Other When is a Map a Map and when is a Map a reference to a Map?

Tim Green

Member
Licensed User
Longtime User
I was recently bitten with a self-inflicted bug when using Map declared data.

I did this:

A_Map = “some content”
Map1 = A_Map
A_Map = “some other content”
Map2 = A_Map​

Expecting that Map1 would then contain “some content” and Map2 would contain “some other content”.

But it was pointed out to me that assigning a Map to a Map is a reference assignment and the above logic results in Map1, Map2, and A_Map all referencing the same “some other content”.

I checked the Beginner’s User Guide, the User Guide, and also the Rapid Android App Development book and did not see an explanation about this. Searching the forums to see if there was more information about “Map” I got swamped with hits for using “Google maps”.

I also see code examples where a Map is used without performing the .Initialize method on the Map, even though the Guides say that this is required. Looking again at these examples it seems that this may be OK if the uninitialized Map is first “assigned” to another Map, which is to say that it becomes a Map reference.

As someone with (too) many years of ‘c’ experience behind me I am quite comfortable with pointers and handling references to values. But perhaps the syntax and rules for using B4A Maps can be made a bit more explicit and obvious?
 

barx

Well-Known Member
Licensed User
Longtime User
I too found out the hard way and it doesn't just relate to maps. All views / collections are the same I believe.
 
Upvote 0

LucaMs

Expert
Licensed User
Longtime User
Perhaps I misunderstood, because I do not see the problem.

The three maps point to the same memory area and therefore have the same content, that is the last added / changed.

An uninitialized map does not work (rightly); try to add some values to it.
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
I did this
B4X:
    ' Scenario 1 (the way you did)
    Dim map1, map2 As Map
    map1.Initialize
    map2.Initialize
     
    Dim mm As Map
    mm.Initialize
    mm.Put("Key","Some content")

    map1 = mm
    ' map1 now is a reference to mm
    mm.Put("Key","Some other content")
    ' i change the same map. map1 now have new content
    map2 = mm
    ' map1 and map2 have the same objectreference (and the same content)

Refactor your code a little bit (create new references each time)

B4X:
    ' Scenario 2
    Dim map1, map2 As Map
    map1.Initialize
    map2.Initialize
 
    Dim mm As Map
    mm.Initialize
    mm.Put("Key","Some content")

    map1 = mm
    ' map1 now is a reference to mm
 
    ' we are creating a NEW reference
    Dim mm As Map
    mm.Put("Key","Some other content")
    ' i change the (new) map. map1 does not change it contents.
    map2 = mm
    ' map1 and map2 now have different objectreferences and due to this it has different content

hope it helps a bit to understand
 
Last edited:
Upvote 0
Top