java1.7 linkedhashmap的结构原理

本文对比了LinkedHashMap和HashMap在创建节点时的不同实现方式,详细解析了两者在节点插入顺序上的区别,LinkedHashMap通过维护一个双向链表来保持元素的插入顺序。

源码基本和hashmap是一样的,只有一个创建节点的方法不同

hashmap的:

    void createEntry(int hash, K key, V value, int bucketIndex) {
        Entry<K,V> e = table[bucketIndex];
        table[bucketIndex] = new Entry<>(hash, key, value, e);
        size++;
    }

linkedhashmap的:

    void createEntry(int hash, K key, V value, int bucketIndex) {
        HashMap.Entry<K,V> old = table[bucketIndex];
        Entry<K,V> e = new Entry<>(hash, key, value, old);
        table[bucketIndex] = e;
        e.addBefore(header);
        size++;
    }    
        private void addBefore(Entry<K,V> existingEntry) {
            after  = existingEntry;
            before = existingEntry.before;
            before.after = this; //this的值为当前插入的节点对象
            after.before = this;
        }
会造成 节点顺序: null -> 第一个节点 -> null -> 第二个节点 。。。

不明白的可断点跟踪查看

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值