awelgorithms

Put if the key is absent

Updated

putIfAbsent(k,v) writes only when k is missing. Present keys keep their value. Size grows only on insert. This is first-wins. Overwrite is last-wins.

What to focus on

First-index maps use this. Caching uses this. Do not implement it as get-null-then-put without locking if threads exist. Here, just the sequential contract.

Worked examples

insert

a = [4, 1] as {4:2,1:8}, putIfAbsent 9→3
  1. 9 missing

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

keep old

a = [4, 1] as {4:2,1:8}, putIfAbsent 1→0
  1. 1 present
  2. 8 stays

Result: {4:2, 1:8}

empty

a = [], putIfAbsent 4→2
  1. insert

Result: {4:2}

Try it

Write putIfAbsent(m, k, v). m is the hash map. k is the key. v is the value. Write only when k is missing. Present keys keep their value. a = [4, 1] as {4:2,1:8}, putIfAbsent 9→3 → {4:2, 1:8, 9:3}. a = [4, 1] as {4:2,1:8}, putIfAbsent 1→0 → {4:2, 1:8}. a = [], putIfAbsent 4→2 → {4:2}.

keys and values are integers. Empty is in the cases.