目录


1.LinkedHashMap的内部结构
2.LinkedHashMap构造函数
3.元素新增策略
4.元素删除
5.元素修改和查找
6.特殊操作
7.扩容
8.总结

1.LinkedHashMap的内部结构

 

 

对象的内部结构其实就是hashmap的内部结构,但是比hashmap的内部结构node要多维护2个引用指针,用来做前置和后置链表

同事linkedhashmap本身还有头链表节点和尾部链表节点

复制代码
static class Entry<K,V> extends MyHashMap.Node<K,V> {     Entry<K,V> before, after;     Entry(int hash, K key, V value, Node<K,V> next) {         super(hash, key, value, next);     } }
复制代码

因为linkedhashmap是继承自hashmap,所以hashmap有的它都有,比如上面2的n次幂,扩容策略等等
那么就有意思了,linkedhashmap有什么独到的地方么???
既然是继承自hashmap,那么我们看看hashmap没有的东西,或者被覆盖重写了的东西即可

 


2.LinkedHashMap构造函数

 

基本和hashmap一致,无法就是设置空间容量,负载因子等数据
这里空间容量和hashmap一样,也是取比当前容量大的最小2次幂

 

3.元素新增策略

 

就说put吧,就是完完全全调用的hashmap的 put方法。。。。晕
不过注意啊,再hashmap中有实打实大三个函数是为了linkedhashmap准备的,这个在源码中就说明了,并且put操作就用到了其中2个

 

 

这里可以吧之前hashmap中的这几个函数加上了解了

还有个地方需要注意,linkedhashmap还重写了newnode方法,这个是为了和链表串联起来

复制代码
Node<K,V> newNode(int hash, K key, V value, Node<K,V> e) {     //每当创建一个新的链表节点的时候,我们调用linknodelast,吧当前添加到链表末尾    TestLinkedHashMap.Entry<K,V> p =            new TestLinkedHashMap.Entry<K,V>(hash, key, value, e);     linkNodeLast(p);     return p; }  //不论这个节点是处于什么位置,都进行添加节点private void linkNodeLast(TestLinkedHashMap.Entry<K,V> p) {     TestLinkedHashMap.Entry<K,V> last = tail;     tail = p;     if (last == null)         head = p;     else {         p.before = last;         last.after = p;     } }
复制代码

 


接下来我们一一阐述hashmap专门为linkedhashmap预留的几个函数

3.1 afterNodeAccess

复制代码
/**  *  * @program: y2019.collection.map.TestLinkedHashMap  * @description: 只有当put进去,这个值存放到hash桶上的时候,并且这个值是之前存在的,(或者是树状结构),才会触发这个函数  * @auther: xiaof  * @date: 2019/8/29 17:03  */void afterNodeAccess(Node<K,V> e) { // move node to last    TestLinkedHashMap.Entry<K,V> last;     if (accessOrder && (last = tail) != e) {