I wanted to implement SoftHashMap based on Java SoftReference and HashMap. Java docs, about WeakHashMap, say that keys are weak references rather than values. I was wondering what hashcode() would be used for put and pull functions of the underlying HashMap. I am assuming WeakHashMap put works like this: hashMap.put(new WeakReference(key), value); If this is true, how would the entry be found for a key.
Wouldn’t it be better if values were wrapped in a WeakReference rather than keys?
If you look at this IBM article, you’ll see that in the possible implementation they give:
put adds an Entry normally – but the Entry is a WeakReference referring to the Key object. If the Key is garbage collected, the Entry will eventually be cleared out by WeakHashMap’s expungeStaleEntries() method, called every so often from other WeakHashMap operations.