if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}
void afterNodeInsertion(boolean evict) { // possibly remove eldest
LinkedHashMap.Entry<K,V> first;
if (evict && (first = head) != null && removeEldestEntry(first)) {
K key = first.key;
removeNode(hash(key), key, null, false, true);
}
}
从put办法中逐渐看上去,最终我们发现,假设 removeEldestEntry(first) 办法前往true,则会移除 head,这样就淘汰了最近都没运用的数据。完全契合LRU。
4 最复杂的LRU完成
依据下面剖析,我们可以如下完成一个最复杂的LRU
public class LRUCache<K,V> extends LinkedHashMap<K,V> {
private int cacheSize;
public LRUCache(int cacheSize) {
// 留意:此处需求让 accessOrder = true
super(cacheSize, 0.75f, true);
this.cacheSize = cacheSize;
}
/**
* 判别元素个数能否超过缓存的容量,超过需求移除
*/
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > cacheSize;
(责任编辑:admin)