LinkedList源码分析

简介: Java中List是一个必须要掌握的基础知识,List是一个接口,实现List接口的基础类有很多,其中最具有代表性的两个:ArrayList和LinkedList。

Java中List是一个必须要掌握的基础知识,List是一个接口,实现List接口的基础类有很多,其中最具有代表性的两个:ArrayList和LinkedList。


01变量


今天主要讲解一下LinkedList的基本数据接口和源码分析。LinkedList的底层则是链表的结构,它可以进行高效的插入和移除的操作,基于一个双向链表的结构。源码变量定义可以看到:


transient int size = 0;
/*** Pointer to first node.* Invariant: (first == null && last == null) ||*            (first.prev == null && first.item != null)*/transient Node<E> first;
/*** Pointer to last node.* Invariant: (first == null && last == null) ||*            (last.next == null && last.item != null)*/transient Node<E> last;



02图结构


用一个图理解一下:LinkedList的Node节点结构

565a552761e902d9ae5c607a7ba84acf_640_wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1.png

prev是存储的上一个节点的引用。

element是存储的具体的内容。

next是存储的下一个节点的引用。

LinkedList的整体结构图

911404c2068986887f544e3641e8132f_640_wx_fmt=png&wxfrom=5&wx_lazy=1&wx_co=1.png


从图解中可以看出,有好多的Node,并且还有first和last这两个变量保存头部和尾部节点的信息。

还有就是它不是一个循环的双向链表,因为他前后都是null,这个也是我们需要注意的地方。


03常用方法


3.1 构造方法:


/**  * Constructs an empty list.  */  public LinkedList() {  //无参构造方法 }
  /**  * Constructs a list containing the elements of the specified  * collection, in the order they are returned by the collection's  * iterator.  *  * @param  c the collection whose elements are to be placed into this list  * @throws NullPointerException if the specified collection is null  */  public LinkedList(Collection<? extends E> c) {  //以集合c形式,把所有元素插入链表中  this();  addAll(c);  }


3.2 添加元素方法:


/**   * Appends the specified element to the end of this list.   *   * <p>This method is equivalent to {@link #addLast}.   *   * @param e element to be appended to this list   * @return {@code true} (as specified by {@link Collection#add})   */   public boolean add(E e) {      linkLast(e);      return true;   }


/** * 将集合插入到链表的尾部 */public boolean addAll(Collection<? extends E> c) {    return addAll(size, c);}
public boolean addAll(int index, Collection<? extends E> c) {    checkPositionIndex(index);
    //获取目标集合转为数组    Object[] a = c.toArray();    //新增元素的数量    int numNew = a.length;    //如果新增元素为0,则不添加,并且返回false    if (numNew == 0)        return false;
    //定义index节点的前置节点,后置节点    Node<E> pred, succ;
    //判断是不是链表的尾部,如果是,那么就在链表尾部追加数据    //尾部的后置节点一定是null,前置节点是队尾    if (index == size) {        succ = null;        pred = last;    } else {
        //如果不是在链表的末尾而是在中间位置的话,        //取出index节点,作为后继节点        succ = node(index);
        //index节点的前节点,作为前驱的节点        pred = succ.prev;    }
    //链表批量的增加,去循环遍历原数组,依次去 插入节点的操作    for (Object o : a) {        @SuppressWarnings("unchecked")         //类型转换        E e = (E) o;        // 前置节点为pred,后置节点为null,当前节点值为e的节点newNode        Node<E> newNode = new Node<>(pred, e, null);        // 如果前置节点为空, 则newNode为头节点,否则为pred的next节点        if (pred == null)            first = newNode;        else            pred.next = newNode;        pred = newNode;    }    // 循环结束后,如果后置节点是null,说明此时是在队尾追加的    if (succ == null) {        last = pred;    } else {        //否则是在队中插入的节点 ,更新前置节点 后置节点        pred.next = succ;        succ.prev = pred;    }    // 修改数量size    size += numNew;    //修改modCount    modCount++;    return true;}


3.3 Node节点:


private static class Node<E> {      //值      E item;      //后者  指向下一节点引用      Node<E> next;      //前者  指向前一节点引用      Node<E> prev;
      Node(Node<E> prev, E element, Node<E> next) {          this.item = element;          this.next = next;          this.prev = prev;    } }

从上述Node节点源码可以看出,LinkedList的链表数据结构,是双向的每个元素既存储着上一个元素的引用又存储着下一个元素的引用。

addAll方法之后我们再看看其他的添加元素的方法,分为了头部addFist和尾部addLast。

addFist(E e)

将e元素添加到链表并且设置其为头节点Fist


public void addFirst(E e) {    linkFirst(e);}
/** * Links e as first element. * 将e元素弄成链接列表的第一个元素 */private void linkFirst(E e) {    final Node<E> f = first;
    //链表开头前驱为空,值为e,后继为f    final Node<E> newNode = new Node<>(null, e, f);    first = newNode;
    //若f为空,则表明列表中还没有元素,last也应该指向newNode    if (f == null)        last = newNode;    else        //否则,前first的前驱指向newNode        f.prev = newNode;    size++;    modCount++;}


3.4 Poll()方法:


/**     * Retrieves and removes the head (first element) of this list.     * 返回链表中第一个元素,如果链表是空,则返回空     * @return the head of this list, or {@code null} if this list is empty     * @since 1.5   */   public E poll() {      final Node<E> f = first;      return (f == null) ? null : unlinkFirst(f);   }


相关文章
|
1天前
|
监控 网络协议 算法
2026年起SSL证书有效期逐年缩短:企业如何避免“续期风暴”!
SSL证书有效期将从2026年起分三阶段逐步缩短至47天,人工续期难以为继。阿里云“WoSign SSL证书+自动化服务”,支持域名监控、自动托管、云产品/服务器一键部署及智能提醒,助力企业高效应对高频续期挑战。
8046 0
|
10天前
|
域名解析 人工智能 Linux
|
20天前
|
Linux Go 开发工具
手机上跑 DeepSeek 智能体:开源安卓客户端 DSH Go 安装与使用指南
DSH Go 是一款开源安卓客户端,将 DeepSeek Harness 智能体引擎装进手机:免 Root、免 Termux,一键安装即用;支持本机运行(内置 Ubuntu+Node.js)或远程接管电脑会话;具备插话打断、过程折叠、屏幕操控、端到端加密分享等特色功能,真正实现智能体“口袋化”。
17990 63
|
18天前
|
人工智能
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
进不去 Antigravity 或 Gemini,提示所在地区不可用?三步查清 Google 账号关联地区、官方更正表单理由选法与改区注意事项。
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
|
4天前
|
人工智能 安全 网络安全
|
1天前
|
人工智能 弹性计算 安全
阿里云 码上2027 AI coding 嘉年华
阿里云“码上2027”AI Coding嘉年华于2026年12月2—3日在上海西岸艺术中心举行,聚焦AI Coding从单点提效迈向企业级研发体系升级。发布Qwen4-max模型、QBot智能协作、AgentCore平台等重磅成果,并推出ECS云服务器特惠(200Mbps流量月付40元起)。
761 0
|
7天前
|
云安全 数据采集 人工智能
|
9天前
|
Linux API iOS开发
【DSH】DeepSeek Harness新手保姆教程(下载+安装+配置+使用,2026最新实测)
DeepSeek Harness(dsh)是 DeepSeek AI 开源的智能体框架,秉持“一切皆插件”理念,支持读文件、改代码、执行命令、处理表格等自动化任务;免费开源,兼容 Win/macOS,需配 API 密钥使用。(239字)
1446 5
|
15天前
|
人工智能 开发工具 开发者
2026最新codex下载安装保姆级使用教程(下载+安装+登录+使用,含所有历史版本)
Codex 是 OpenAI 推出的开源 AI 编程智能体,跑在本地终端和桌面客户端里,能读懂整个代码仓库,一句自然语言就能让它改代码、执行命令、跑测试、修 Bug,支持 Windows、macOS、Linux 三大平台。本文把 Codex下载、安装、登录、汉化、基础使用一次讲全,并整理了国内用户最常踩的坑,跟着做 10 分钟就能跑起来。
2556 8
|
20天前
|
弹性计算 人工智能 API
Codex超详细入门指南(下载·安装·登录·上手,全版本覆盖,2026最新版)
建议收藏本教程,2026 全年各版本更新随时回来查阅。如果你在搭建过程中遇到任何问题,欢迎结合 阿里云工单系统 提交技术支持请求,或在 阿里云开发者社区 搜索 Codex 相关话题交流。 祝你编码愉快,效率翻倍!
4050 22