前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >LinkedHashMap源码分析

LinkedHashMap源码分析

作者头像
算法之名
发布2020-05-26 15:18:25
3300
发布2020-05-26 15:18:25
举报
文章被收录于专栏:算法之名算法之名

我们都知道HashMap是无序的Map,TreeMap是有序的Map。而LinkedHashMap继承于HashMap,也是一个有序的Map,这似乎违背了Hash的理论。(注:TreeMap和LinkedHashMap的有序性是不一样的,TreeMap的根据Key的大小来排序的,而LinkedHashMap是根据put的先后顺序来排序的)

我们来看这么一个例子

public class LinkedHashMapTest {
    public static void main(String[] args) {
        Map<String,String> test = new HashMap<>();
        test.put("化学","93");
        test.put("数学","98");
        test.put("生物","92");
        test.put("英语","97");
        test.put("物理","94");
        test.put("历史","96");
        test.put("语文","99");
        test.put("地理","95");
        test.entrySet().stream().forEach(entry -> System.out.println(entry.getKey() + ":" +
                entry.getValue()));
        System.out.println("----------------");
        Map<String,String> test1 = new LinkedHashMap<>();
        test1.put("化学","93");
        test1.put("数学","98");
        test1.put("生物","92");
        test1.put("英语","97");
        test1.put("物理","94");
        test1.put("历史","96");
        test1.put("语文","99");
        test1.put("地理","95");
        test1.entrySet().stream().forEach(entry -> System.out.println(entry.getKey() + ":" +
                entry.getValue()));

    }
}

运行结果

物理:94 生物:92 历史:96 化学:93 数学:98 语文:99 英语:97 地理:95 ---------------- 化学:93 数学:98 生物:92 英语:97 物理:94 历史:96 语文:99 地理:95

我们来看一下LinkedHashMap的源码,首先它是继承于HashMap

public class LinkedHashMap<K,V>
    extends HashMap<K,V>
    implements Map<K,V>

然后它的节点是一个带有双向链表前后节点的属性,继承了HashMap的Node节点类,只是对HashMap的Node节点做了扩展,以便在LinkedHashMap的整体双向链表的数据结构体系中进行使用。

在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中

static class Node<K,V> implements Map.Entry<K,V> {
    final int hash;
    final K key;
    V value;
    Node<K,V> next;

    Node(int hash, K key, V value, Node<K,V> next) {
        this.hash = hash;
        this.key = key;
        this.value = value;
        this.next = next;
    }

    public final K getKey()        { return key; }
    public final V getValue()      { return value; }
    public final String toString() { return key + "=" + value; }

    public final int hashCode() {
        return Objects.hashCode(key) ^ Objects.hashCode(value);
    }

    public final V setValue(V newValue) {
        V oldValue = value;
        value = newValue;
        return oldValue;
    }

    public final boolean equals(Object o) {
        if (o == this)
            return true;
        if (o instanceof Map.Entry) {
            Map.Entry<?,?> e = (Map.Entry<?,?>)o;
            if (Objects.equals(key, e.getKey()) &&
                Objects.equals(value, e.getValue()))
                return true;
        }
        return false;
    }
}

不仅节点是双向链表,它本身的数据结构跟HashMap最大的不同,HashMap是由一个可扩容的动态数组来构架的,而LinkedHashMap维护了两套数据结构体系来构架,一个就是HashMap的可扩容的动态数组,还有一个就是双向链表。

在HashMap中

transient Node<K,V>[] table;

在LinkedHashMap中

transient LinkedHashMap.Entry<K,V> head;
transient LinkedHashMap.Entry<K,V> tail;

由于继承于HashMap,LinkedHashMap没有重写put()方法

在HashMap中

public V put(K key, V value) {
    return putVal(hash(key), key, value, false, true);
}
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
               boolean evict) {
    Node<K,V>[] tab; Node<K,V> p; int n, i;
    //如果表为空,rehash全表
    if ((tab = table) == null || (n = tab.length) == 0)
        n = (tab = resize()).length;
    //如果表的该hash位置为空,新建节点
    if ((p = tab[i = (n - 1) & hash]) == null)
        tab[i] = newNode(hash, key, value, null);
    else {
        Node<K,V> e; K k;
        //如果Hash冲突,且插入的key与节点key相同,将新节点p赋给e
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            e = p;
        //如果p为红黑树节点,将红黑树节点p赋给e
        else if (p instanceof TreeNode)
            e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
        //否则即为链表节点,进行相应处理
        else {
            for (int binCount = 0; ; ++binCount) {
                //如果数组Hash位置的节点的下一个节点为空
                if ((e = p.next) == null) {
                    //在该位置的下一个节点生成一个新的节点
                    p.next = newNode(hash, key, value, null);
                    if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
                        treeifyBin(tab, hash);
                    //跳出无限循环
                    break;
                }
                //如果下一个节点不为空,且该节点的哈希值,key值均与传入的值相等
                if (e.hash == hash &&
                    ((k = e.key) == key || (key != null && key.equals(k))))
                    //跳出无限循环
                    break;
                p = e;
            }
        }
        if (e != null) { //如果存在相同的key的映射,替换掉旧值,并返回旧值
            V oldValue = e.value;
            if (!onlyIfAbsent || oldValue == null)
                e.value = value;
            afterNodeAccess(e);
            return oldValue;
        }
    }
    ++modCount;
    //达到边界值进行扩容
    if (++size > threshold)
        resize();
    afterNodeInsertion(evict);
    return null;
}

我们在putVal()方法中可以看到有一个newNode()的方法,则LinkedHashMap重写了该方法newNode()

在LinkedHashMap中

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

在HashMap中

Node<K,V> newNode(int hash, K key, V value, Node<K,V> next) {
    return new Node<>(hash, key, value, next);
}

我们在HashMap的put()方法中看到有两个方法afterNodeAccess(e),afterNodeInsertion(evict);

void afterNodeAccess(Node<K,V> p) { }
void afterNodeInsertion(boolean evict) { }

它们在HashMap中的方法体为空。

而在LinkedHashMap中也重写了这两个方法

final boolean accessOrder; //LinkedHashMap的的迭代排序方法,true对于访问顺序,false对于插入顺序
void afterNodeAccess(Node<K,V> e) { //将节点e移动到尾部
    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;
        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;
    }
}
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);
    }
}
protected boolean removeEldestEntry(Map.Entry<K,V> eldest) {
    return false;
}

虽然LinkedHashMap重写了get()方法,但是主体跟HashMap并没有区别,只是读取完之后的节点放到了双向链表的尾部

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

由此我们可以看出,LinkedHashMap并不是从双向链表中来读取数据,而是在动态数组中来读取的,所以它的读取的时间复杂度并没有变成O(n),依然为O(1)。而双向链表体系只是维护了一个顺序性,仅此而已。

对于删除,LinkedHashMap也没有重写remove()方法,但是在HashMap的remove()方法中有一个afterNodeRemoval()的方法。

在HashMap中

public V remove(Object key) {
    Node<K,V> e;
    return (e = removeNode(hash(key), key, null, false, true)) == null ?
        null : e.value;
}
final Node<K,V> removeNode(int hash, Object key, Object value,
                           boolean matchValue, boolean movable) {
    Node<K,V>[] tab; Node<K,V> p; int n, index;
    if ((tab = table) != null && (n = tab.length) > 0 &&
        (p = tab[index = (n - 1) & hash]) != null) {
        Node<K,V> node = null, e; K k; V v;
        if (p.hash == hash &&
            ((k = p.key) == key || (key != null && key.equals(k))))
            node = p;
        else if ((e = p.next) != null) {
            if (p instanceof TreeNode)
                node = ((TreeNode<K,V>)p).getTreeNode(hash, key);
            else {
                do {
                    if (e.hash == hash &&
                        ((k = e.key) == key ||
                         (key != null && key.equals(k)))) {
                        node = e;
                        break;
                    }
                    p = e;
                } while ((e = e.next) != null);
            }
        }
        if (node != null && (!matchValue || (v = node.value) == value ||
                             (value != null && value.equals(v)))) {
            if (node instanceof TreeNode)
                ((TreeNode<K,V>)node).removeTreeNode(this, tab, movable);
            else if (node == p)
                tab[index] = node.next;
            else
                p.next = node.next;
            ++modCount;
            --size;
            afterNodeRemoval(node);
            return node;
        }
    }
    return null;
}

afterNodeRemoval()方法在HashMap中方法体也是空的

void afterNodeRemoval(Node<K,V> p) { }

所以LinkedHashMap重写了该方法

在LinkedHashMap中

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;
    if (b == null)
        head = a;
    else
        b.after = a;
    if (a == null)
        tail = b;
    else
        a.before = b;
}

当然最重要的就是检测LinkedHashMap和HashMap的EntrySet或者KeySet是否有序,我们以EntrySet的forEach方法来比较

在HashMap中,我们可以看到它是对整个数组不为空的节点进行全序遍历,由于节点在数组中的哈希值的大小不确定,所以无法做到按照插入顺序来排序。

public final void forEach(Consumer<? super Map.Entry<K,V>> action) {
    Node<K,V>[] tab;
    if (action == null)
        throw new NullPointerException();
    if (size > 0 && (tab = table) != null) {
        int mc = modCount;
        for (int i = 0; i < tab.length; ++i) {
            for (Node<K,V> e = tab[i]; e != null; e = e.next)
                action.accept(e);
        }
        if (modCount != mc)
            throw new ConcurrentModificationException();
    }
}

在LinkedHashMap中,我们可以看到,它是按照从双向链表的头节点head开始,逐步向下一个节点进行遍历的,所以它是严格按照插入顺序来取值的。

public final void forEach(Consumer<? super Map.Entry<K,V>> action) {
    if (action == null)
        throw new NullPointerException();
    int mc = modCount;
    for (LinkedHashMap.Entry<K,V> e = head; e != null; e = e.after)
        action.accept(e);
    if (modCount != mc)
        throw new ConcurrentModificationException();
}

最后LinkedHashMap同HashMap一样,不具备线程安全性,所以在多线程环境下它是不安全的。

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档