MATLAB Answers

# Updating containers.Map with a new containers.Map - does new key overwrite old?

16 views (last 30 days)
Nathan Thern on 31 Aug 2018
I refer to the Read and Write Using Key Index documentation.
A new containers.Map can be created by combining two containers.Map:
m1 = containers.Map({1, 5, 8}, {'A', 'B', 'C'});
m2 = containers.Map({8, 9, 6}, {'X', 'Y', 'Z'});
m = [m1; m2];
keys(m), values(m)
ans =
    
ans =
'A' 'B' 'Z' 'X' 'Y'
Note that value 'C' for key 8 was overwritten. In the same way I could update Map m1 with the key/value pairs in m2:
m1 = [m1; m2];
keys(m1), values(m1)
ans =
    
ans =
'A' 'B' 'Z' 'X' 'Y'
What I would like to know (the documentation isn't clear on this) is:
Is it guaranteed that the value in m2 will overwrite any duplicate key values from m1.
I could take the question a step further with this example:
m1 = containers.Map({1, 5, 8}, {'A', 'B', 'C'});
m2 = containers.Map({8, 9, 6}, {'X', 'Y', 'Z'});
m3 = containers.Map({2, 8, 3}, {'Q', 'R', 'S'});
m1 = [m1; m2; m3];
keys(m1), values(m1)
ans =
      
ans =
'A' 'Q' 'S' 'B' 'Z' 'R' 'Y'
It seems that the last appearing value for the key 8 becomes the new value. But is that guaranteed, and will it always be that way in the future?
##### 0 CommentsShowHide -1 older comments

Sign in to comment.

### Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!