Jdk1.8集合框架之LinkedHashMap源码解析

LinkedHashMap和HashMap的区别

LinkedHashMap是HashMap的子类,它和HashMap的区别是,可以按照节点插入的自然顺序(或者节点的操作顺序)来迭代所有节点。而且它的迭代比HashMap更快,因为HashMap遍历的数据结构要复杂一点,而LinkedHashMap用一个双链表来迭代。

HashMap的迭代器

HashMap的三种迭代器都是HashIterator的子类。

final class KeyIterator extends HashIterator
    implements Iterator<K> {
    public final K next() { return nextNode().key; }
}

final class ValueIterator extends HashIterator
    implements Iterator<V> {
    public final V next() { return nextNode().value; }
}

final class EntryIterator extends HashIterator
    implements Iterator<Map.Entry<K,V>> {
    public final Map.Entry<K,V> next() { return nextNode(); }
}

HashIterator抽象类

从源码可知,迭代器访问元素的顺序是从桶位数组第0位开始往后逐个桶位寻找,每个桶中的结构要么是单链表要么是实现了红黑树的双链表,都是链式结构,所以右可以逐个寻找。这也就是HashMap中元素的访问顺序,和hash&table.length、hash值和Key值都有关系。

abstract class HashIterator {
    Node<K,V> next;        // next entry to return
    Node<K,V> current;     // current entry
    int expectedModCount;  // for fast-fail
    int index;             // current slot

    HashIterator() {
        expectedModCount = modCount;
        Node<K,V>[] t = table;
        current = next = null;
        index = 0;
        // 初始化next指向第一个节点
        if (t != null && size > 0) { // advance to first entry
            do {} while (index < t.length && (next = t[index++]) == null);
        }
    }

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

    final Node<K,V> nextNode() {
        Node<K,V>[] t;
        Node<K,V> e = next;
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        if (e == null)
            throw new NoSuchElementException();
        // 将next指向下一个节点
        if ((next = (current = e).next) == null && (t = table) != null) {
            do {} while (index < t.length && (next = t[index++]) == null);
        }
        return e;
    }

    public final void remove() {
        Node<K,V> p = current;
        if (p == null)
            throw new IllegalStateException();
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        current = null;
        K key = p.key;
        removeNode(hash(key), key, null, false, false);
        expectedModCount = modCount;
    }
}

LinkedHashMap的迭代器

LinkedHashMap是HashMap的子类,在HashMap的迭代器之上有添加了自己的迭代器,都是继承自LinkedHashIterator。

final class LinkedKeyIterator extends LinkedHashIterator
    implements Iterator<K> {
    public final K next() { return nextNode().getKey(); }
}

final class LinkedValueIterator extends LinkedHashIterator
    implements Iterator<V> {
    public final V next() { return nextNode().value; }
}

final class LinkedEntryIterator extends LinkedHashIterator
    implements Iterator<Map.Entry<K,V>> {
    public final Map.Entry<K,V> next() { return nextNode(); }
}

LinkedHashIterator抽象类的原理很简单,就是在双链表中依次访问。

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

    LinkedHashIterator() {
        next = head;
        expectedModCount = modCount;
        current = null;
    }

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

    final LinkedHashMap.Entry<K,V> nextNode() {
        LinkedHashMap.Entry<K,V> e = next;
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        if (e == null)
            throw new NoSuchElementException();
        current = e;
        next = e.after;
        return e;
    }

    public final void remove() {
        Node<K,V> p = current;
        if (p == null)
            throw new IllegalStateException();
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
        current = null;
        K key = p.key;
        removeNode(hash(key), key, null, false, false);
        expectedModCount = modCount;
    }
}

LinkedHashMap.Entry

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);
    }
}
// 双链表头结点
transient LinkedHashMap.Entry<K,V> head;

// 双链表尾节点
transient LinkedHashMap.Entry<K,V> tail;

// 迭代器的访问顺序,true表示按访问顺序,false表示按照元素的插入顺序
// 在构造时指定,默认为false,指定后不能修改,决定了双链表的存储顺序
final boolean accessOrder;

看一个例子来展示accessOrder的影响:

LinkedHashMap<String,Integer> map  = 
        new LinkedHashMap<>(10, 0.75f, true);
map.put("gaoxiang1", 1);
map.put("gaoxiang3", 2);
map.put("gaoxiang4", 3);
map.put("gaoxiang2", 4);
map.put("gaoxiang0", 5);
map.put("gaoxiang", 6);
map.get("gaoxiang4");
map.get("gaoxiang1");
System.out.println(map); 
//{gaoxiang3=2, gaoxiang2=4, gaoxiang0=5, gaoxiang=6, gaoxiang4=3, gaoxiang1=1}

保存插入顺序和访问顺序

那么双链表又是如何保存插入顺序的呢?

我们看看HashMap的源码,发现在putVal方法结束前调用了afterNodeAccessafterNodeInsertion方法,在removeNode方法结束前调用了afterNodeRemoval方法,在其他方法中也多次使用下面的三个方法,而这三个都是空方法。它们是为LinkedHashMap留下的。

// Callbacks to allow LinkedHashMap post-actions
void afterNodeAccess(Node<K,V> p) { }
void afterNodeInsertion(boolean evict) { }
void afterNodeRemoval(Node<K,V> p) { }

LinkedHashMap重写了这3个方法:

// 从双链表中删除e节点
void afterNodeRemoval(Node<K,V> e) { 
    LinkedHashMap.Entry<K,V> p =
        (LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after;
    p.before = p.after = null;
    // 将e.before和e.after连接起来
    if (b == null) // e是头结点时
        head = a;
    else
        b.after = a;
    if (a == null) // e是尾结点时
        tail = b;
    else
        a.before = b;
}

// removeEldestEntry方法返回值总是false,所以该方法没有任何效果
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);
    }
}

// 记录节点的访问顺序
void afterNodeAccess(Node<K,V> e) { 
    LinkedHashMap.Entry<K,V> last;
    // 如果accesOrder指定为true,访问节点后会将双链表中该节点移动到最后
    if (accessOrder && (last = tail) != e) {
        LinkedHashMap.Entry<K,V> p =
            (LinkedHashMap.Entry<K,V>)e, b = p.before, a = p.after;
        p.after = null;
        if (b == null)
            head = a;
        else
            b.after = a;
        if (a != null)
            a.before = b;
        else
            last = b;
        if (last == null)
            head = p;
        else {
            p.before = last;
            last.after = p;
        }
        tail = p;
        ++modCount;
    }
}

删除节点时,HashMap的removeNode方法会调用afterNodeRemoval,从双链表中删除该节点。

插入新节点时,HashMap的putVal方法中会调用newNode方法,而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);
    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;
    }
}

而每次有效访问节点都会调用afterNodeAccess方法,记录访问顺序。

public V get(Object key) {
    Node<K,V> e;
    if ((e = getNode(hash(key), key)) == null)
        return null;
    if (accessOrder)
        afterNodeAccess(e);
    return e.value;
}


上一篇:Jdk1.8集合框架之HashMap源码解析(详细解析红黑树)
下一篇:JDK1.8并发之synchronized和Lock

猜你喜欢

转载自blog.csdn.net/weixin_40255793/article/details/80773670