awelgorithms

Copy a hash map

Updated

Copying allocates a new map and puts each (k,v) from the original. Mutating the copy's keys or scalar values must not change the original.

What to focus on

A shallow copy shares nested objects: if the value is a list, b.get(k).append(x) mutates a's list too. Deep copy clones those values. b = a is alias, not copy.

Worked examples

scalars

a = [4, 1, 9] as {4:2,1:8,9:3}, b = copy(a), put b 1→0
  1. a still 1→8

Result: independent scalars

then overwrite original

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

Result: a write misses b

empty

a = [], b = copy(a)
  1. both {}

Result: {}

Try it

Write copy(a). a is a hash map of key to value. Return a new map with the same pairs. Changing b must not change a for scalar values. If values are lists, a shallow copy still shares those lists. a = [4, 1, 9] as {4:2,1:8,9:3}, b = copy(a), put b 1→0 → independent scalars. a = [4, 1, 9] as {4:2,1:8,9:3}, b = copy, put a 4→0 → a write misses b. a = [], b = copy(a) → {}.

keys are integers. Empty is in the cases.