首先LinkedHashMap就是继承了HashMap,在此基础上维护一个双向链表,实现也很简单,就是对Entry进行改造:
/**
* LinkedHashMap entry.
*/
private static class Entry<K,V> extends HashMap.Entry<K,V> {
// These fields comprise the doubly linked list used for iteration.
Entry<K,V> before, after;
Entry(int hash, K key, V value, HashMap.Entry<K,V> next) {
super(hash, key, value, next);
}
/**
* Removes this entry from the linked list.
*/
private void remove() {
before.after = after;
after.before = before;
}
/**
* Inserts this entry before the specified existing entry in the list.
*/
private void addBefore(Entry<K,V> existingEntry) {
after = existingEntry;
before = existingEntry.before;
before.after = this;
after.before = this;
}
/**
* This method is invoked by the superclass whenever the value
* of a pre-existing entry is read by Map.get or modified by Map.set.
* If the enclosing Map is access-ordered, it moves the entry
* to the end of the list; otherwise, it does nothing.
*/
void recordAccess(HashMap<K,V> m) {
LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m;
if (lm.accessOrder) {
lm.modCount++;
remove();
addBefore(lm.header);
}
}
void recordRemoval(HashMap<K,V> m) {
remove();
}
}
上面就是LinkedHashMap对entry的改造,关键是重写了recordAccess(),当使用LRU时(即accessOrder==true),先用remove()将自己从链表中摘出来,再调addBefore()把自己加到队列头
LRU在put和get时,都有可能执行把元素位置改变的操作,而LinkedHashMap的put和get是从HashMap继承过来的,那么实现此操作的方法recordAccess()就在HashMap的put()和get()中被调用。
public V put(K key, V value) {
if (table == EMPTY_TABLE) {
inflateTable(threshold);
}
if (key == null)
return putForNullKey(value);
int hash = hash(key);
int i = indexFor(hash, table.length);
for (Entry<K,V> e = table[i]; e != null; e = e.next) {
Object k;
if (e.hash == hash && ((k = e.key) == key || key.equals(k))) {
V oldValue = e.value;
e.value = value;
e.recordAccess(this);
return oldValue;
}
}
modCount++;
addEntry(hash, key, value, i);
return null;
}
LinkedHashMap默认没有打开LRU模式,启用LRU通过boolean accessOrder控制,设置accessOrder通过调用构造函数实现:
public LinkedHashMap(int initialCapacity,
float loadFactor,
boolean accessOrder) {
super(initialCapacity, loadFactor);
this.accessOrder = accessOrder;
}
因此我们要用LRU的LinkedHashMap时,通过此构造函数就能按最近最少访问方式存放数据了。但还没完,真正实现LRU还差了队列满的时候删除队尾元素的步骤。
LinkedHashMap提供了一个removeEldestEntry方法:
protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
return false;
}
默认是return false的,此方法在LinkedHashMap的addEntry中被调用,如果removeEldestEntry返回true,将执行删除此元素操作:
void addEntry(int hash, K key, V value, int bucketIndex) {
super.addEntry(hash, key, value, bucketIndex);
// Remove eldest entry if instructed
Entry<K,V> eldest = header.after;
if (removeEldestEntry(eldest)) {
removeEntryForKey(eldest.key);
}
}
找到队尾元素非常方便,就是header.after。
上面说到LinkedHashMap的removeEldestEntry默认返回时false的,要让它返回true,就需要我们继承LinkedHashMap重写该方法了:
class LRUMap<K,V> extends LinkedHashMap<K, V> implements Map<K, V>{
int capacity;
public LRUMap(int capacity) {
super(16, (float) 0.75, true);
this.capacity = capacity;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K,V> eldest){
if(size() > capacity){
return true;
}
return false;
}
}
此时我们对LRUMap的操作就是以LRU模式存储元素了。