基础知识(二) LinkedHashMap 源码详解


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

知识点
     LinkedHashMap 继承了 HashMap 最主要的区别就是有序。内部使用散列链表 红黑树实现。注意此Map不是线程安全的,如果需要同步使用请使用ConcurrentHashMap 或者 Collections.synchronizedMap.
     其实它内部使用的还是HashMap的方法,主要区别在以下三个方法中。

// 节点访问后、节点插入后、节点移除后做一些事情。
void afterNodeAccess(Node<K,V> p) { }
void afterNodeInsertion(boolean evict) { }
void afterNodeRemoval(Node<K,V> p) { }

常量参数

很多常量用的都是他爸的

//继承了HashMap Node 内部定义两个参数 
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 ; //双向链表的尾对象数据

源码解析

//其实就是一个移动链表的过程
 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;
            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;
        }
    }


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

架构技术专栏

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值