gpt4 book ai didi

Java SoftHashMap 实现

转载 作者:行者123 更新时间:2023-12-02 00:39:05 27 4
gpt4 key购买 nike

我想基于 Java SoftReferenceHashMap 实现 SoftHashMap。关于 WeakHashMap 的 Java 文档说键是弱引用而不是值。我想知道底层 HashMap 的 put 和 pull 函数将使用什么 hashcode() 。我假设 WeakHashMap put 的工作原理如下: hashMap.put(new WeakReference(key), value); 如果这是真的,那么如何找到键的条目.

如果将值包装在 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 是一个引用 Key 对象的 WeakReference。如果 Key 被垃圾回收,Entry 最终将被 WeakHashMap 的 expungeStaleEntries() 方法清除,该方法经常从其他 WeakHashMap 操作中调用。

关于Java SoftHashMap 实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6885950/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com