Java开发之LinkedList源码分析

#来自ゾフィー(佐菲)

1 简介

LinkedList 的底层数据结构是双向链表。可以当作链表、栈、队列、双端队列来使用。有以下特点:

  • 在插入或删除数据时,性能好;
  • 允许有 null 值;
  • 查询效率不高;
  • 线程不安全;
复制代码
public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{}

2 源码

LinkedList 数据结构:

复制代码
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;
     }
}

LinkedList 两个构造函数:

复制代码
public LinkedList() {}

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

addAll()

复制代码
 public boolean addAll(int index, Collection<? extends E> c) {
        //校验 index 是否合理
        checkPositionIndex(index);
        
        Object[] a = c.toArray();
        int numNew = a.length;
        if (numNew == 0)
            return false;
       //succ:待添加节点的位置。
       //pred:待添加节点的前驱节点。  
        Node<E> pred, succ;
        if (index == size) {//在末尾插入
            succ = null;
            pred = last;
        } else { //不在末尾插入
            succ = node(index); //这个方法 会折半
            pred = succ.prev;
        }

        for (Object o : a) {
            //创建新节点
            @SuppressWarnings("unchecked") E e = (E) o;
            Node<E> newNode = new Node<>(pred, e, null);
            if (pred == null)
                first = newNode;
            else
                pred.next = newNode;
            pred = newNode;
        }

        if (succ == null) {
            last = pred;
        } else {
            pred.next = succ;
            succ.prev = pred;
        }
        //把集合的大小设置为新的大小 
        size += numNew;
        modCount++;
        return true;
    }

get() -> 会有折半

复制代码
public E get(int index) {
     //校验 index 是否越界
      checkElementIndex(index);
      return node(index).item;
}

Node<E> node(int index) {
        // assert isElementIndex(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;
        }
    }

add()

复制代码
public boolean add(E e) {
   //在末尾追加元素的方法。
    linkLast(e);
    return true;
}

void linkLast(E e) {
      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++;//size 自增
      modCount++;
}

remove()

复制代码
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;
}

//删除节点
E unlink(Node<E> x) {
      // assert x != null;
      final E element = x.item;
      final Node<E> next = x.next;
      final Node<E> prev = x.prev;
      //1 -> 2 -> 3      1 -> 3
      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;
 }

toArray()

复制代码
public Object[] toArray() {
       //创建一个新数组 然后遍历链表,将每个元素存在数组里,返回
       Object[] result = new Object[size];
       int i = 0;
       for (Node<E> x = first; x != null; x = x.next)
           result[i++] = x.item;
       return result;
}
相关推荐
Data_agent16 小时前
京东商品价格历史信息API使用指南
java·大数据·前端·数据库·python
云技纵横16 小时前
Stream API 从入门到实践:常用操作、易错点与性能建议
开发语言·windows·python
Knight_AL16 小时前
Java 17 新特性深度解析:记录类、密封类、模式匹配与增强的 switch 表达式对比 Java 8
java·开发语言
最贪吃的虎16 小时前
Spring Boot 自动装配(Auto-Configuration)深度实现原理全解析
java·运维·spring boot·后端·mysql
Ahuuua16 小时前
Spring Bean作用域深度解析
java·后端·spring
大学生资源网16 小时前
基于Vue的网上购物管理系统的设计与实现(java+vue+源码+文档)
java·前端·vue.js·spring boot·后端·源码
吴佳浩 Alben16 小时前
Go 1.25.5 通关讲解
开发语言·后端·golang
XXYBMOOO16 小时前
理解 C++ 中的字节序转换函数 `swapEndian`
开发语言·arm开发·c++
小高Baby@16 小时前
深入理解golang的GMP模型
开发语言·后端·golang
qq_124987075316 小时前
基于微信小程序的私房菜定制上门服务系统(源码+论文+部署+安装)
java·spring boot·微信小程序·小程序·毕业设计·毕设