我想基于Java SoftHashMapSoftReference实现HashMap。关于WeakHashMap的Java文档说,键是弱引用,而不是值。我想知道什么hashcode()用于基础HashMap的放置和拉出功能。我假设WeakHashMap put的工作方式如下:hashMap.put(new WeakReference(key), value);如果为true,将如何找到键的条目。

如果将值包装在WeakReference中而不是键中会更好吗?

最佳答案

如果查看此IBM article,您会发现它们在可能的实现中给出:

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是一个WeakReference,它引用Key对象。如果Key是垃圾回收,则最终将通过WeakHashMap的expungeStaleEntries()方法清除该条目,该方法经常从其他WeakHashMap操作中调用。

09-10 09:18
查看更多