GENGEN
主页
vuepress
  • GIT命令
  • python+django
  • vue cli搭建项目
  • babel es6转换es5
  • docker aliyun配置
  • npm 配置
  • linux 常用命令
  • Ubuntu 下Linux 命令
  • github
  • gitee
  • csdn
  • 关于我
主页
vuepress
  • GIT命令
  • python+django
  • vue cli搭建项目
  • babel es6转换es5
  • docker aliyun配置
  • npm 配置
  • linux 常用命令
  • Ubuntu 下Linux 命令
  • github
  • gitee
  • csdn
  • 关于我
  • java基础

    • JDK8 函数式编程
    • JDK8 新特性之Date-Time
    • Servlet 源码分析
    • ArrayList 源码
    • LinkedList 源码
    • HashMap 源码
    • String 源码
    • BigDecimal 源码
    • java 类的加载
    • Class 源码
    • Synchronized锁升级
    • 事务的传播机制
    • knowledge
  • JAVA WEB

    • Java Servlet
    • 权限设计
    • logback日志的链路追踪
  • DATABASE

    • MySQL EXPLAIN详解
    • MySQL 索引
    • MySQL 表锁、行锁
    • MySQL ACID与transcation
    • 分布式事务
    • MySQL MVCC机制
    • Mysql 乐观锁与悲观锁
    • 分布式锁1 数据库分布式锁
    • 分布式锁2 Redis分布式锁
    • 分布式锁3 ZK分布式锁
  • SpringCloud

    • SpringCloud服务注册中心之Eureka
    • SpringCloud服务注册中心之Zookeeper
    • SpringCloud服务调用之Ribbon
    • SpringCloud服务调用之OpenFeign
    • SpringCloud服务降级之Hystrix
    • SpringCloud服务网关之Gateway
    • SpringCloud Config分布式配置中心
    • SpringCloud服务总线之Bus
    • SpringCloud消息驱动之Stream
    • SpringCloud链路追踪之Sleuth
    • SpringCloud Alibaba Nacos
    • SpringCloud Alibaba Sentinel
  • Spring

    • SpringBoot
    • Spring-data-jpa入门
    • SpringCloud问题
    • dispatcherServlet 源码分析
    • @SpringBootApplication注解内部实现与原理
    • spring启动初始化初始化
  • 中间件

    • 分布式协调服务器Zookeeper
    • 服务治理Dubbo
    • 分布式配置管理平台Apollo
    • 消息中间件框架Kafka
    • 分布式调度平台ElasticJob
    • 可视化分析工具Kibana
    • ElacticSearch 基础
    • ElacticSearch进阶
    • ElacticSearch集成
  • 环境部署

    • 应用容器引擎Docker
    • DockerCompose服务编排
    • 负载均衡Nginx
    • Nginx的安装配置
    • K8S基础
  • 代码片段

    • listener 监听模式
    • spingboot 整合redis
    • XSS过滤
    • profile的使用
    • ConfigurationProperties注解
  • 设计模式

    • 工厂模式
    • 单例模式
    • 装饰者模式
    • 适配器模式
    • 模板方法模式
    • 观察者模式
  • 读书笔记

    • 《Spring in Action 4》 读书笔记
    • 《高性能mysql》 读书笔记
  • NoSQL

    • Redis基础
    • Redis高级
    • Redis集群
    • Redis应用
  • MQ

    • rabbitMQ基础
    • rabbitMQ高级
    • rabbitMQ集群
  • JVM

    • JVM体系架构概述
    • 堆参数调整
    • GC 分代收集算法
    • JVM 垃圾回收器
    • JVM 相关问题
  • JUC

    • JUC总览
    • volatile关键字
    • CAS
    • ABA问题
    • collections包下线程安全的集合类
    • Lock 锁
    • LockSupport
    • AQS
    • Fork/Join分支框架
    • JUC tools
    • BlockingQueue 阻塞队列
    • Executor 线程池
    • CompletableFuture
    • 死锁以及问题定位分析
  • Shell

    • shell命令
    • shell基础
  • Activiti

    • IDEA下的Activiti HelloWord
    • 流程定义的CRUD
    • 流程实例的执行
    • 流程变量
  • VUE

    • vue基础
    • vue router
    • Vuex
    • Axios 跨域
    • dialog 弹出框使用
    • vue 动态刷新页面
    • vue 封装分页组件
    • vue 动态菜单
    • vue 常用传值
  • Solidity 智能合约

    • Solidity 基础
    • Solidity ERC-20
    • Solidity 101
  • English

    • 时态

LinkedList 源码解析 JDK8

概述

  • LinkedList 是一个继承 AbstractSequentialList的双向链表,它也可以被当作堆栈、队列或者双端队列进行操作。

  • LinkedList 实现了 List接口,能对它进行队列操作。

  • LinkedList 实现了 Deque接口,能将它当作双端队列使用。

  • LinkedList 实现了 Cloneable java.io.Serializable接口,意味着它能够克隆以及序列化传输。

变量

/**
 *集合元素数量
 */
 transient int size = 0;
/**
*链表头节点
*/
transient Node<E> first;
/**
*链表尾节点
*/
transient Node<E> last;

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;
    }
}

Tips

Node结构,包含三个元素,数据item,上一个节点prev,下一个节点next
每个Node都包含上一个以及下一个的节点信息

构造器

public LinkedList() {
    }

public LinkedList(Collection< extends E> c) {
        this();
        addAll(c);
    }        

API

  • 增

    public void addFirst(E e) {
          linkFirst(e);
      }
    
    private void linkFirst(E e) {
      final Node<E> f = first;//获取原来第一个
      final Node<E> newNode = new Node<>(null, e, f);
      first = newNode;//newNode设置为first
      if (f == null)//如果之前空list
          last = newNode;
      else
          f.prev = newNode;//原来第一个,既现在第二个的上一个指向新的Node
      size++;
      modCount++;
    }  
    
    public void addLast(E e) {
          linkLast(e);
      }
    
    void linkLast(E e) {//跟linkFirst操作相反
      final Node<E> l = last;
      final Node<E> newNode = new Node<>(l, e, null);
      last = newNode;
      if (l == null)
          first = newNode;
      else
          l.next = newNode;
      size++;
      modCount++;
    }  
    
    public boolean add(E e) {
          linkLast(e);//跟addLast一样,增加返回值
          return true;
      }
    
    public void add(int index, E element) {
        checkPositionIndex(index);//检查下标是否越界
    
        if (index == size)//index是最后一个,尾部追加
            linkLast(element);
        else
            linkBefore(element, node(index));
    }
    
    //node 二分法,for循环查找下标index的元素
    Node<E> node(int index) {
         
        if (index < (size >> 1)) {
            Node<E> x = first;
            for (int i = 0; i < index; i++)
                x = x.next;
            return x;
        } else {
            Node<E> x = last;
            for (int i = size - 1; i > index; i--)
                x = x.prev;
            return x;
        }
    }
    
    void linkBefore(E e, Node<E> succ) {
          final Node<E> pred = succ.prev;//获取此下标的上一个
          final Node<E> newNode = new Node<>(pred, e, succ);//构建一个新Node
          succ.prev = newNode;//把原下标的Node指向更改
          if (pred == null)
              first = newNode;
          else
              pred.next = newNode;
          size++;
          modCount++;
      }
    
    public boolean addAll(Collection< extends E> c) {
          return addAll(size, c);
    }
    
    public boolean addAll(int index, Collection< extends E> c) {
      checkPositionIndex(index);//检查越界 [0,size] 闭区间
    
      Object[] a = c.toArray();//转化为数组
      int numNew = a.length;
      if (numNew == 0)//如果新增元素数量为0,则不增加,并返回false
          return false;
    
      Node<E> pred, succ; //index节点的前置节点,后置节点
      if (index == size) {//构造器走这个条件分支,链表尾部追加数据
          succ = null;
          pred = last;//pred = 最后一个节点值
      } else {
          succ = node(index);//取出index节点,作为后置节点
          pred = succ.prev;//前置节点是,index节点的前一个节点
      }
    
      for (Object o : a) {//链表批量增加,是靠for循环遍历原数组,依次执行插入节点操作
          @SuppressWarnings("unchecked") E e = (E) o;
          //构造新Node,之前最后一个节点为上一个,下一个节点为Null
          Node<E> newNode = new Node<>(pred, e, null);
          if (pred == null)//之前LinkedList为空,说明是头结点
              first = newNode;
          else//否则 前置节点的后置节点设置问新节点
              pred.next = newNode;//给pred的next赋值newNode
          pred = newNode;
      }
    
      if (succ == null) {//循环结束后,判断,如果后置节点是null。 说明此时是在队尾append的。
          last = pred;
      } else {// 否则是在队中插入的节点 ,更新前置节点 后置节点
          pred.next = succ;
          succ.prev = pred;
      }
    
      size += numNew;
      modCount++;
      return true;
    }
    
  • 删

    public E removeFirst() {
          final Node<E> f = first;
          if (f == null)
              throw new NoSuchElementException();
          return unlinkFirst(f);
      }
    
    private E unlinkFirst(Node<E> f) {
          final E element = f.item;//获取第一个Node的item
          final Node<E> next = f.next;//拿到下一个Node
          f.item = null;
          f.next = null; // 置为null
          first = next; //first重新指向
          if (next == null)//判断next是否null
              last = null;
          else//next变first,它上一个为null
              next.prev = null;
          size--;
          modCount++;
          return element;
      }  
    
    public E removeLast() {
          final Node<E> l = last;
          if (l == null)
              throw new NoSuchElementException();
          return unlinkLast(l);
      }
    
    private E unlinkLast(Node<E> l) {
          // 跟unlinkFirst相反操作
          final E element = l.item;
          final Node<E> prev = l.prev;
          l.item = null;
          l.prev = null; // help GC
          last = prev;
          if (prev == null)
              first = null;
          else
              prev.next = null;
          size--;
          modCount++;
          return element;
      }  
    
    //for循环查找o是否与集合中元素equals
    public boolean remove(Object o) {
          if (o == null) {
              for (Node<E> x = first; x != null; x = x.next) {
                  if (x.item == null) {
                      unlink(x);
                      return true;
                  }
              }
          } else {
              for (Node<E> x = first; x != null; x = x.next) {
                  if (o.equals(x.item)) {
                      unlink(x);
                      return true;
                  }
              }
          }
          return false;
      }
    
    //移除item元素,重新prev next重新指向
    E unlink(Node<E> x) {
          final E element = x.item;
          final Node<E> next = x.next;
          final Node<E> prev = x.prev;
    
          if (prev == null) {//是不是第一个
              first = next;
          } else {
              prev.next = next;
              x.prev = null;
          }
    
          if (next == null) {//是不是最后一个
              last = prev;
          } else {
              next.prev = prev;
              x.next = null;
          }
    
          x.item = null;
          size--;
          modCount++;
          return element;
      }  
    
    public E remove(int index) {
        checkElementIndex(index);
        return unlink(node(index));
    }
    
    public void clear() {
          // 循环 Node置null
          for (Node<E> x = first; x != null; ) {
              Node<E> next = x.next;
              x.item = null;
              x.next = null;
              x.prev = null;
              x = next;
          }
          first = last = null;
          size = 0;
          modCount++;
      }
    
  • 查

    public E getFirst() {
          final Node<E> f = first;
          if (f == null)
              throw new NoSuchElementException();
          return f.item;
      }
    
    public E getLast() {
          final Node<E> l = last;
          if (l == null)
              throw new NoSuchElementException();
          return l.item;
      }
    
    public E get(int index) {
          checkElementIndex(index);
          return node(index).item;
      }
    
  • 改

    public E set(int index, E element) {
          checkElementIndex(index);
          Node<E> x = node(index);
          E oldVal = x.item;
          x.item = element;
          return oldVal;
      }
    
  • 包含contains

public boolean contains(Object o) {
    return indexOf(o) != -1;
}

public int indexOf(Object o) {
    int index = 0;
    if (o == null) {
        for (Node<E> x = first; x != null; x = x.next) {
            if (x.item == null)
                return index;
            index++;
        }
    } else {
        for (Node<E> x = first; x != null; x = x.next) {
            if (o.equals(x.item))
                return index;
            index++;
        }
    }
    return -1;
}    
  • 迭代器 ListIterator
public ListIterator<E> listIterator(int index) {
    checkPositionIndex(index);
    return new ListItr(index);
}

private class ListItr implements ListIterator<E> {
    private Node<E> lastReturned;
    private Node<E> next;
    private int nextIndex;
    private int expectedModCount = modCount;

    ListItr(int index) {
        // assert isPositionIndex(index);
        next = (index == size) ? null : node(index);
        nextIndex = index;
    }

    public boolean hasNext() {
        return nextIndex < size;
    }

    public E next() {
        checkForComodification();
        if (!hasNext())
            throw new NoSuchElementException();

        lastReturned = next;
        next = next.next;
        nextIndex++;
        return lastReturned.item;
    }

    public boolean hasPrevious() {
        return nextIndex > 0;
    }

    public E previous() {
        checkForComodification();
        if (!hasPrevious())
            throw new NoSuchElementException();

        lastReturned = next = (next == null) ? last : next.prev;
        nextIndex--;
        return lastReturned.item;
    }

    public int nextIndex() {
        return nextIndex;
    }

    public int previousIndex() {
        return nextIndex - 1;
    }

    public void remove() {
        checkForComodification();
        if (lastReturned == null)
            throw new IllegalStateException();

        Node<E> lastNext = lastReturned.next;
        unlink(lastReturned);
        if (next == lastReturned)
            next = lastNext;
        else
            nextIndex--;
        lastReturned = null;
        expectedModCount++;
    }

    public void set(E e) {
        if (lastReturned == null)
            throw new IllegalStateException();
        checkForComodification();
        lastReturned.item = e;
    }

    public void add(E e) {
        checkForComodification();
        lastReturned = null;
        if (next == null)
            linkLast(e);
        else
            linkBefore(e, next);
        nextIndex++;
        expectedModCount++;
    }

    public void forEachRemaining(Consumer< super E> action) {
        Objects.requireNonNull(action);
        while (modCount == expectedModCount && nextIndex < size) {
            action.accept(next.item);
            lastReturned = next;
            next = next.next;
            nextIndex++;
        }
        checkForComodification();
    }

    final void checkForComodification() {
        if (modCount != expectedModCount)
            throw new ConcurrentModificationException();
    }
}

总结

  • 由代码可知,要操作首位两端的数字,是比较简单的
  • 对于有 (int index) 的操作,都要 node(int index) 循环,根据next prev指向查找下标index的元素
  • 越靠近中间的数据获取速度越慢
  • LinkedList 查询慢是因为数据在内存中是不连续的,循环迭代查找起来就比较慢。
Last Updated:
Contributors: 88395515, wangs
Prev
ArrayList 源码
Next
HashMap 源码