Collection集合-LinkedHashMap

继承类和实现接口

可以看出LinkedHashMap继承了HashMap,那么主要方法都是和HashMap相同,那么主要看相对于HashMap重写了那些方法就能确定LinkedHashMap相对于HashMap的特征

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

存储数据的Entry类进行重写

新增:新增两个参数before,after 记录当前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;

   /**
   * The tail (youngest) of the doubly linked list.
   */
  transient LinkedHashMap.Entry<K,V> tail;

新建节点的方法重写

这里是相对于HashMap最大的不同

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;
        //最后一个tail节点为空,插入值就为head节点
        if (last == null)
            head = p;
        else {
            //节点链式存储前后节点地址
            p.before = last;
            last.after = p;
        }
    }

总结

    1. LinkedHashMap继承HashMap,所以主要方法和HashMap是相通的
    1. LinkedHashMap重写了存储数据的Entry节点结构,增加了记录当前节点的前后节点位置
    1. LinkedHashMap新增了head和tail两个节点,在存储数据创建节点的时候存储首位节点位置
    1. LinkedHashMap内部顺序结构是通过双向链表关联起来的
posted @   PerfectLi  阅读(3)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 25岁的心里话
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
点击右上角即可分享
微信分享提示