0

我想SoftHashMap基于 JavaSoftReferenceHashMap. Java 文档,关于 WeakHashMap,说键是弱引用而不是值。我想知道什么hashcode()将用于底层的 put 和 pull 函数HashMap。我假设WeakHashMapput 的工作方式是这样的:hashMap.put(new WeakReference(key), value);如果这是真的,如何找到密钥的条目。

如果值被包装在 aWeakReference而不是键中会不会更好?

4

1 回答 1

3

如果您查看这篇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 操作中调用。

于 2011-07-30T21:16:38.193 回答