Skip to main content

HashMap lookup code solution

The issue with the code below is that the MapInner object is mutated after its added as a key to the collection.  If the key is modified after its been added to HashSet or HashMap, the behavior of HashMap lookup is undefined.

Also mutating the key can lead to memory leaks.  This would happen if the collection object is in memory and there are no references to the key.

Solution here is to use immutable objects as key.

Map<MapInner, Integer> m = new HashMap<>();
MapInner mi = new MapInner(0,1);
m.put(mi, 0);
mi.setI(2);

Comments