JDK8—LinkedHashMap源码浅析

来源:互联网 发布:超级计算机 云计算 编辑:程序博客网 时间:2024/06/06 01:54

本篇文章叫做浅析,只是为了分析下LinkedHanshMap是如何保持有序的。

LinkedHashMap有一个子类:

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);        }    }

这个类继承了HashMap的Node类,可以看到,这个类只有两个属性,before,after都是Entry类型的。就是通过这个Entry类型来维护其链表结构的有序性,但这个链表是什么时候插入的呢,我们去看下hashMap的put方法,其中有这么一段:
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)            tab[i] = newNode(hash, key, value, null);
在插入的时候创建了一个newNode,newNode代码进入了Lin可达HashMap类,如下:

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);        linkNodeLast(p);        return p;    }
private void linkNodeLast(LinkedHashMap.Entry<K,V> p) {        LinkedHashMap.Entry<K,V> last = tail;        tail = p;        if (last == null)            head = p;        else {            p.before = last;            last.after = p;        }    }

可以看到在此处进行了链表的有序插入。

如果想继续深入研究,推荐一篇博文,虽然介绍的很粗略,但写出了精髓:

http://blog.csdn.net/u013124587/article/details/52659741


原创粉丝点击