如果您查看这篇IBM 文章,您会发现在他们给出的可能实现中:
public class WeakHashMap<K,V> implements Map<K,V> {
private static class Entry<K,V> extends WeakReference<K>
implements Map.Entry<K,V> {
private V value;
private final int hash;
private Entry<K,V> next;
...
}
public V get(Object key) {
int hash = getHash(key);
Entry<K,V> e = getChain(hash);
while (e != null) {
K eKey= e.get();
if (e.hash == hash && (key == eKey || key.equals(eKey)))
return e.value;
e = e.next;
}
return null;
}
put 通常会添加一个 Entry - 但该 Entry 是一个引用 Key 对象的 WeakReference。如果 Key 被垃圾回收,Entry 最终会被 WeakHashMap 的 expungeStaleEntries() 方法清除,该方法经常从其他 WeakHashMap 操作中调用。