awelgorithms

Overwrite the value for a key

Updated

A second put with the same key replaces the value. The old value is gone. Size does not change. This is the map contract, not a bug, unless you meant to group or count.

What to focus on

If you needed both values, you should have stored a list under the key, not a scalar. Overwrite is last-write-wins.

Worked examples

replace 8

a = [4, 1, 9] as {4:2,1:8,9:3}, put 1→0
  1. 1 still the key
  2. 8 discarded

Result: {4:2, 1:0, 9:3}

same value again

a = [4] as {4:2}, put 4→2
  1. no visible change
  2. still size 1

Result: {4:2}

empty cannot overwrite

a = [], put 4→2
  1. there was no old value
  2. this is insert

Result: {4:2}

Try it

Write put(m, k, v). m is the hash map. k is a key that already exists. v is the new value. Replace the value. Size does not change. Last write wins. a = [4, 1, 9] as {4:2,1:8,9:3}, put 1→0 → {4:2, 1:0, 9:3}. a = [4] as {4:2}, put 4→2 → {4:2}. a = [], put 4→2 → {4:2}.

keys and values are integers. The key already exists.