LinkedHashMap 源码解读

我看的JDK1.8的源码

先从下面得示例开始

public class LinkedHashMapDemo {

    public static void main(String[]args){

        Map m = new HashMap();
        m.put(2, "b");
        m.put(1, "a");
        m.put(3, "c");

        Set set = m.keySet();
        Iterator keyit =set.iterator();
        while(keyit.hasNext()){
            int key = (Integer)keyit.next();
            System.out.println(key + " : " + m.get(key));
        }

        System.out.println("====================");

        Map m2 = new LinkedHashMap();
        m2.put(2, "b");
        m2.put(1, "a");
        m2.put(3, "c");
        Set set2 = m2.keySet();
        Iterator keyit2 =set2.iterator();
        while(keyit2.hasNext()){
            int key = (Integer)keyit2.next();
            System.out.println(key + " : " + m2.get(key));
        }
    }
}

运行后结果

1 : a
2 : b
3 : c
====================
2 : b
1 : a
3 : c

由结果可知LinkedHashMap 记录了key的插入顺序,那么LinkedHashMap是如何做到的呢?
分析源码

public class LinkedHashMap<K,V>
    extends HashMap<K,V>
    implements Map<K,V>{
    transient LinkedHashMap.Entry<K,V> head;
    transient LinkedHashMap.Entry<K,V> tail;
}

LinkedHashMap.Entry

static class Entry<K,V> extends HashMap.Node<K,V> {
      Entry<K,V> before, after;
      Entry(int hash, K key, V value, Node<K,V> next){
            super(hash, key, value, next);
        }
 }

LinkedHashMap 里多了head ,tail .
head和tail都是LinkedHashMap.Entry,
LinkedHashMap.Entry继承HashMap.Node,
只不过在它的基础上多了before,after的引用,before就是前面插入的节点,after就是后面插入的节点。形成了双链表的结构。

因此可以想象出keyset的遍历肯定是从head开始
如果是我来写,我的代码是如下,返回的是list.
为什么jdk的keyset返回的是set结构?有上面好处,该问题留待后面看了set的结构后再来分析。

//我的想象中的代码
public List keySet(){
 LinkedHashMap.Entry<K,V> entry;
 List list = ArrayList();
 if(head==null)
  return null;
 else
  list.add(head.getKey);
 while((entry=head.after)!=null){
    list.add(entry.getKey);
 }
 return list;
}

那jdk里的keyset如何实现的,继续看LinkedHashMap 的keyset方法

 public Set<K> keySet() {
        Set<K> ks = keySet;
        if (ks == null) {
            ks = new LinkedKeySet();
            keySet = ks;
        }
        return ks;
    }

下面是我们经常调用的iterator

final class LinkedKeySet extends AbstractSet<K> {
        ...
        public final Iterator<K> iterator() {
            return new LinkedKeyIterator();
        }
        ...
    }

我们调用的iterator.next()

final class LinkedKeyIterator extends LinkedHashIterator
        implements Iterator<K> {
        //!!!nextNode()是LinkedHashIterator里的一个方法
        public final K next() { return nextNode().getKey(); }
    }

这里为什么LinkedHashIterator是abstract?没明白

abstract class LinkedHashIterator {
        LinkedHashMap.Entry<K,V> next;
        LinkedHashMap.Entry<K,V> current;
        int expectedModCount;

        LinkedHashIterator() {
           //构造函数里将LinkedHashMap里的head赋值给next
            next = head;
            expectedModCount = modCount;
            current = null;
        }

        public final boolean hasNext() {
            return next != null;
        }

        //就是这里了,原理其实和我想象中是一样的。不过jdk 实现的要很的多
        final LinkedHashMap.Entry<K,V> nextNode() {
            LinkedHashMap.Entry<K,V> e = next;
            //在遍历的过程中不能做插入或删除linkedHashMap的操作,否则会报
            ConcurrentModificationException
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
            if (e == null)
                throw new NoSuchElementException();
            current = e;
            //每次调用next()都将e.after赋给next
            next = e.after;
            return e;
        }

遍历的过程看完了,可是都没用到tail?那tail拿来做什么用?

继续看插入的方法,看之前回想下hashMap的插入key ,value实现 :

1.如果key的hash算法^(n-1)得到得数组下标里元素是null,即单链表得头元素为空,则直接new 一个node 加入

2.如果不为空,则遍历单链表,如果整个单链表里节点都没有和key相等,则new 一个node插入到单链表头,把头节点放入数组里

3.如果有key相等则替换

既然linkedHashMap 里多了head 和 tail 想都能想到肯定是1和2里操作里把双向链表的顺序关系补上。
hashmap里的put方法的注解过程,具体的分析过程见
http://blog.csdn.net/guo_xl/article/details/78817285

下面的注解是对应LinkedHashMap里不同的地方

 final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
                   boolean evict) {
  Node<K,V>[] tab; Node<K,V> p; int n, i;
        if ((tab = table) == null || (n = tab.length) == 0)
            n = (tab = resize()).length;
        if ((p = tab[i = (n - 1) & hash]) == null)
        //!!对应上面的分析1,linkedhashmap重写newNode
            tab[i] = newNode(hash, key, value, null);
        else {
            Node<K,V> e; K k;
            if (p.hash == hash &&
                ((k = p.key) == key || (key != null && key.equals(k))))
                e = p;
            else if (p instanceof TreeNode)
                e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
            else {
                for (int binCount = 0; ; ++binCount) {
                    if ((e = p.next) == null) {
                    //!!对应上面的分析2,linkedhashmap重写了newNode
                        p.next = newNode(hash, key, value, null);
                        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) { 
            //!!对应上面的分析3,linkedhashmap重写afterNodeAccess
                V oldValue = e.value;
                if (!onlyIfAbsent || oldValue == null)
                    e.value = value;
                    //如果accessorder=true的话,需要在afterNodeAccess这个方法里去做LRU算法
                afterNodeAccess(e);
                return oldValue;
            }
        }
        ++modCount;
        if (++size > threshold)
            resize();
        afterNodeInsertion(evict);
        return null;

linkedHashMap 里的newNode方法

 Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) {
        LinkedHashMap.Entry<K,V> p =
            new LinkedHashMap.Entry<K,V>(hash, key, value, e);
        //!!!维持了head,tail的关系 
        linkNodeLast(p);
        return p;
    }

linkedHashMap 里linkNodeLast方法

private void linkNodeLast(LinkedHashMap.Entry<K,V> p) {
        LinkedHashMap.Entry<K,V> last = tail;
        //tail现在是p了
        tail = p;
        //第一次加,tail为空,则head,tail都指向p
        if (last == null)
            head = p;
        else {
           //p的before为上个tail
            p.before = last;
            //上个tail 的after为p
            last.after = p;
        }
    }

LRU 算法:最近最少访问到最近最多访问的顺序来排列。
换一句话就是
当某个节点被访过就放到双链表的最后面

void afterNodeAccess(Node<K,V> e) { // move node to last 访问后把节点放到最后
        LinkedHashMap.Entry<K,V> last;
        if (accessOrder && (last = tail) != e) {
            LinkedHashMap.Entry<K,V> p =
                (LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after;
            //访问过的节点放最后,最后的after肯定是null    
            p.after = null;
            //如果访问的节点是头节点,则访问的节点的after节点就变成了头节点
            if (b == null)
                head = a;
            else
            //如果不是,则访问节点从链表移动到最后,它的after 指向了它的next
                b.after = a;
            //如果访问节点的after不是null,访问节点的after的before就指向了访问节点的before
            if (a != null)              
                a.before = b;
            else
            //否则的话就是访问的末节点了
                last = b;
            //这里是链表里只有一个节点的情况    
            if (last == null)
                head = p;
            else {
            //不是的话就把访问节点的before指向last
                p.before = last;
                //last的after指向了访问节点
                last.after = p;
            }
            //tail 就是访问的节点了
            tail = p;
            ++modCount;
        }
    }

上面的算法就是囊括了链条中各个节点被访问后的情况,注释写的比较乱。
就是以下4种情况
1. a 访问 a
2. a<->b 访问a
3. b<->a<->c 访问a
4. b<->c<->a 访问a
在纸上画个图,,结合上面的算法推演下就知道了。

猜你喜欢

转载自blog.csdn.net/guo_xl/article/details/78858959