JDK 8 LinkedList 源码解析

本文详细介绍了LinkedList的存储结构、类定义、属性、构造函数、链表节点及常用方法,如add、remove等。作为双端链表,LinkedList在插入和删除操作上效率高于ArrayList,但在随机访问上较慢。同时,它实现了Deque接口,支持队列和栈的功能。此外,文章还探讨了LinkedList的迭代器实现和最佳实践。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

【本文是为了梳理知识的总结性文章,总结了一些自认为相关的重要知识点,只为巩固记忆以及技术交流,忘批评指正。其中参考了很多前辈的文章,包括图片也是引用,如有冒犯,侵删。】

目录

0 存储结构

1 类定义

2 属性

3 构造函数

4 链表节点

5常用方法

add(E e)

 addFirst (E e)

add(int index,E element)

addAll(Collection c) 

get(int index)

获取头结点方法

获取尾节点

set(int index,E element)

remove(Object o)

remove(int index)

删除头节点

删除尾节点

clear()

6 迭代器

7 最佳实践


0 存储结构

从底层实现来看,LinkedList是链表实现的,其本质是双向链表。与ArrayList相比,LinkedList的插入和删除速度更快,但是随机访问速度则很慢。LinkedList的优点在于可以将零散的内存单元通过附加引用的方式关联起来,形成按链路顺序查找的线性结构,内存利用率较高。

1 类定义

除了继承AbstractSequentialList抽象类外,LinkedList还实现了另外一个接口Deque,既double-ended queue。这个接口同时具有队列和栈的性质。

âjava linkedlist 类继æ¿å¾âçå¾çæç´¢ç»æ

public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable

2 属性

    // 集合元素数量
    transient int size = 0;

    // 链表头节点
    transient Node<E> first;
    // 链表尾节点
    transient Node<E> last;

3 构造函数

    /**
     * 空构造方法
     */
    public LinkedList() {
    }

    /**
     * 用已有的集合创建链表的构造方法
     */
    public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }

4 链表节点

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

5常用方法

add(E e)

把元素插入链表的末尾,逻辑简单的链表操作

    public boolean add(E e) {
        linkLast(e);
        return true;
    }

    /**
     * 把e加入链表末尾
     */
    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++;
        modCount++;
    }

 addFirst (E e)

将元素加入链表前端,逻辑简单的链表操作


    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;
        if (f == null)
            last = newNode;
        else
            f.prev = newNode;
        size++;
        modCount++;
    }

add(int index,E element)

在指定位置添加元素

    public void add(int index, E element) {
        //检查index是否合法
        checkPositionIndex(index); 

        if (index == size)
            linkLast(element); //添加在链表尾部
        else
            linkBefore(element, node(index)); //添加在链表中间
    }
    

checkPositionIndex()方法检查边界

    private void checkPositionIndex(int index) {
        // 不合法索引直接抛出异常
        if (!isPositionIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
    // 检查index 的边界,由于可以再头和尾插入,因此等号成立
    private boolean isPositionIndex(int index) {
        return index >= 0 && index <= size;
    }

node(int index) 方法在指定元素前面插入元素,由于LinkedList 是双端链表,首先判断index里那一头近,然后从近的一头开始索引,减少遍历次数。

    // 返回指定索引处非空节点
    Node<E> node(int index) {
        // assert isElementIndex(index);
        
        // 由于是双端链表,首先判断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;
        }
    }

linkBefore(E e, Node<E> succ) 在制定的节点succ前插入节点e。

    void linkBefore(E e, Node<E> succ) {
        // assert succ != null;
        final Node<E> pred = succ.prev;
        final Node<E> newNode = new Node<>(pred, e, succ);
        succ.prev = newNode;
        if (pred == null)
            first = newNode;
        else
            pred.next = newNode;
        size++;
        modCount++;
    }

addAll(Collection<? extends E> c) 

将集合插入到链表尾部

  1. 检查插入位置index是否在size之内
  2. 将集合的数据存到对象数组中
  3. 得到插入位置的前驱节点和后继节点
  4. 遍历数据将数据逐个插入
 public boolean addAll(Collection<? extends E> c) {
        // 在链表末尾进行插入,传入的index为size
        return addAll(size, c);
    }
 // 在制定的index前面插入集合中的元素
 public boolean addAll(int index, Collection<? extends E> c) {
        checkPositionIndex(index);

        Object[] a = c.toArray(); // 将集合转为数组
        int numNew = a.length;
        if (numNew == 0)
            return false;
        
        // 根据插入位置的不同确定pred和succ
        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(int index)

检查边界后,直接使用node(index)找到对于的节点的值。

    public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }

checkElementIndex()检查get方法的index是否合法


    private void checkElementIndex(int index) {
        if (!isElementIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }
    // 由于是索引,所以size的等号不成立
    private boolean isElementIndex(int index) {
        return index >= 0 && index < size;
    }

获取头结点方法

getFirst()、element()、peek()、peekFirst() 这四个方法大同小异,都是用来获取头结点的。

由于LinkedList同时具有队列和栈的性质,因此提供这些看似冗余的方法,也是为了它在用于队列或者栈时可以和以前的方法名兼容。至于在实现上的区别,提现在对链表为空时的处理上,getFirst() 和 element() 方法将会在链表为空时抛出NoSuchElementException异常。peek()和peekFirst() 则不会抛出异常,直接返回为null。

    // 如果队列为空会抛出异常
    public E getFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return f.item;
    }
    // 如果队列为空会抛出异常
    public E element() {
        return getFirst();
    }
    // 
    public E peek() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
    }
    //
    public E peekFirst() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
     }

获取尾节点

    // 抛出异常
    public E getLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return l.item;
    }
    // 返回null
    public E peekLast() {
        final Node<E> l = last;
        return (l == null) ? null : l.item;
    }

set(int index,E element)

 public E set(int index, E element) {
        // 检查index是否合法
        checkElementIndex(index);
        // 找到指定节点
        Node<E> x = node(index);
        // 更新值
        E oldVal = x.item;
        x.item = element;
        return oldVal;
    }

remove(Object o)

删除指定元素,先找到其在链表中的位置,然后调用unlink方法移除。

    public boolean remove(Object o) {
        // 如果删除对象为null
        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;
    }

unlink方法移除找的元素

  1. 找到该节点的前驱和后继;
  2. 删除前驱节点;
  3. 删除后继节点;
  4. 将该节点的属性都置为null;
  5. 将size减一;

    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;//得到前驱节点

        // 删除前驱指针
        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;
    }

remove(int index)

删除指定位置的元素

    public E remove(int index) {
        // 检查index范围
        checkElementIndex(index);
        // 将节点删除
        return unlink(node(index));
    }

删除头节点

两个删除头节点方法pop和remove都只调用了removeFirst方法。

 

    public E pop() {
        return removeFirst();
    }

    public E remove() {
        return removeFirst();
    }

removeFirst()方法

    public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        // 头结点不为空就调用unlinkFirst方法移除头结点
        return unlinkFirst(f);
    }
    
    private E unlinkFirst(Node<E> f) {
        // assert f == first && f != null;
        // 将头节点的属性置为null,有助GC
        final E element = f.item;
        final Node<E> next = f.next;
        f.item = null;
        f.next = null; // help GC
        // 头结点指向原头结点的下一个元素
        first = next;
        if (next == null)
            last = null;
        else
            next.prev = null;
        size--;
        modCount++;
        return element;
    }

删除尾节点

两个删除尾节点方法removeLast和popLast都调用了unlinkLast方法进行删除,有一点区别在于removeLast方法在尾节点为空时会抛出NoSuchElementException异常,而pollLast则会返回空。

    public E removeLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return unlinkLast(l);
    }
    
    public E pollLast() {
        final Node<E> l = last;
        return (l == null) ? null : unlinkLast(l);
    }

unlinkLast方法删除尾节点

    private E unlinkLast(Node<E> l) {
        // assert l == last && l != null;
        // 将尾节点属性置空,有助GC
        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;
    }

clear()

遍历链表,将节点中的所有前驱和后继连接关系都置为null。

    public void clear() {
        // 清除节点间的前驱和后继不是必须的,但是为了更好的GC,最好都清除了
        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++;
    }

6 迭代器

LinkedList里面提供了两种迭代器,分别是ListIterator和Iterator。

内部类ListItr实现了ListIterator接口,具有双向遍历能力。

private class ListItr implements ListIterator<E> {
        private Node<E> lastReturned; // 上次返回的值
        private Node<E> next;         // 下一个要返回的值
        private int nextIndex;        // 下一个索引值
        private int expectedModCount = modCount; // 存储迭代器创建时刻的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();
        }
        // LinkedList不是线程安全的,如果多线程在修改链表则快速失败
        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

内部类DescendingIterator 实现了Iterator接口,里面调用了ListItr迭代器,是一个向前遍历的迭代器。

     private class DescendingIterator implements Iterator<E> {
        private final ListItr itr = new ListItr(size());
        public boolean hasNext() {
            return itr.hasPrevious();
        }
        public E next() {
            return itr.previous();
        }
        public void remove() {
            itr.remove();
        }
    }

 

7 最佳实践

  1. LinkedList 底层使用双向队列实现,随机查询较慢,插入速度,删除速度快,适合频繁更改结构的场景。

参考文献

  1. https://pengxiaolei.com/2018/05/14/20180514-java-linkedlist/
  2. https://github.com/Snailclimb/JavaGuide/blob/master/docs/java/LinkedList.md
  3. 《码出高效 Java开发手册》
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值