LinkedHashMap源码浅析(四)

2014-11-24 02:03:54 · 作者: · 浏览: 2
r {@code null} if this map contains no mapping for the key.

*

*

More formally, if this map contains a mapping from a key

* {@code k} to a value {@code v} such that {@code (key==null k==null :

* key.equals(k))}, then this method returns {@code v}; otherwise

* it returns {@code null}. (There can be at most one such mapping.)

*

*

A return value of {@code null} does not necessarily

* indicate that the map contains no mapping for the key; it's also

* possible that the map explicitly maps the key to {@code null}.

* The {@link #containsKey containsKey} operation may be used to

* distinguish these two cases.

*/

public V get(Object key)

{

Entry e = (Entry)getEntry(key);

if (e == null)

return null;

e.recordAccess(this);

return e.value;

}

/**

* 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 m)

{

LinkedHashMap lm = (LinkedHashMap)m;

if (lm.accessOrder)

{

lm.modCount++;

remove();

addBefore(lm.header);

}

}

/**

* Removes this entry from the linked list.

*/

private void remove()

{

before.after = after;

after.before = before;

}

这里我们来看一下recordAccess方法!

上面我们不是讲过accessOrder这个参数值控制着LinkedHashMap的迭代顺序嘛,这里我们来看一下。

当accessOrder为true时,remove方法就是将当前元素从双向链表中移除,

addBefore方法再将当前元素插入到链表的头部去,这样最近读到的元素,在迭代的时候是优先被迭代出来的!

这就是所谓的LRU算法(Least Recently Used):最近最少使用