java8 LinkedList源码阅读

阅读了LinkedList源码的实现,并对源码做了相关注释,如下:
以下内容基于jdk1.8.0_121的ArrayList的源码。
【如果觉得代码太长,可直接看另一篇《 java8 LinkedList源码阅读【2】- 总结》】

/*
 * LinkedList 源码阅读
 * Created by wbin on 2017/4/16.
 */

package java.util;

import java.util.function.Consumer;

public class LinkedList<E>
        extends AbstractSequentialList<E>
        implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
    //链表节点个数
    transient int size = 0;

    //头节点指针
    transient Node<E> first;

    //尾节点指针
    transient Node<E> last;

    //默认构造方法,空链表
    public LinkedList() {
    }

    //构造一个包含指定集合的元素的列表,如果为空则抛出异常NullPointerException
    public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }

    //指定元素作为头节点,即向表头插入新节点
    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++;  //链表结构改变,modCount++
    }

    //指定元素作为尾节点,类比linkFirst(E 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++;
    }

    //在指定节点succ前插入新节点
    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)   //如果指定节点succ为头节点,则新节点为头节点
            first = newNode;
        else    //否则更新前节点的后继指针
            pred.next = newNode;
        size++;
        modCount++;
    }

    //删除头节点f,必须保证 f == first && f != null(内部调用)
    private E unlinkFirst(Node<E> f) {
        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    //否则新头节点的前驱为null
            next.prev = null;
        size--;
        modCount++;     //涉及链表结构改变,modCount++
        return element;
    }

    //删除尾节点l,类比unlinkFirst(Node<E> l)
    private E unlinkLast(Node<E> l) {
        // assert l == last && l != null;
        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;
    }

    //删除指定节点x(x不为空),并返回指定元素的值
    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) {     //如果prev为null,说明删除节点为头节点
            first = next;       //头节点重新赋值为后继节点
        } else {
            prev.next = next;   //更新前驱节点的后继为当前节点的后继
            x.prev = null;
        }

        if (next == null) {     //如果后继节点为null,说明删除节点为尾节点
            last = prev;        //则尾节点重新赋值为前驱节点
        } else {
            next.prev = prev;   //更新后继节点的前驱为当前节点的前驱
            x.next = null;
        }

        x.item = null;
        size--;
        modCount++;     //涉及链表结构改变,modCount++
        return element;
    }

    //返回头节点,如果链表为空,则抛出异常NoSuchElementException
    public E getFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return f.item;
    }

    //返回尾节点,如果链表为空,则抛出异常NoSuchElementException
    public E getLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return l.item;
    }

    //删除头节点,利用上述unlinkFirst()方法,如果链表为空抛出异常NoSuchElementException
    public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
    }

    //删除尾节点,利用上述unlinkLast()方法,如果链表为空抛出异常NoSuchElementException
    public E removeLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return unlinkLast(l);
    }

    //插入新的表头节点
    public void addFirst(E e) {
        linkFirst(e);
    }

    //插入新的表尾节点
    public void addLast(E e) {
        linkLast(e);
    }

    //判断链表是否包含o,利用indexOf()
    public boolean contains(Object o) {
        return indexOf(o) != -1;
    }

    //返回链表元素个数
    public int size() {
        return size;
    }

    //在链表尾部添加新节点
    public boolean add(E e) {
        linkLast(e);
        return true;
    }

    //删除在链表首次出现的指定元素(遍历的方式),会根据是否为null使用不同方式判断(加快比较)。
    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;
    }

    //添加一个集合的元素到末端,若要添加的集合为空返回false
    public boolean addAll(Collection<? extends E> c) {
        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)    //如果插入集合为空则返回false
            return false;

        Node<E> pred, succ; //succ指向当前需要插入节点的位置,pred指向其前一个节点
        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; //pred指针向后移动,指向下一个需插入节点位置的前一个节点
        }

        if (succ == null) {
            last = pred;
        } else {
            pred.next = succ;
            succ.prev = pred;
        }

        size += numNew;
        modCount++; //涉及链表结构改变,modCount++
        return true;
    }

    //清空链表
    public void clear() {
        // Clearing all of the links between nodes is "unnecessary", but:
        // - helps a generational GC if the discarded nodes inhabit
        //   more than one generation
        // - is sure to free memory even if there is a reachable Iterator
        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 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;
    }

    // 在指定位置插入新节点
    public void add(int index, E element) {
        checkPositionIndex(index);  //检查位置合法性

        if (index == size)      //链表尾部插入
            linkLast(element);
        else
            linkBefore(element, node(index));
    }

    // 删除指定位置节点
    public E remove(int index) {
        checkElementIndex(index);   //检查位置合法性
        return unlink(node(index)); //通过node(index)获得指定位置的节点后,调用unlink(Node)删除指定节点
    }

    //判断节点下标合法性
    private boolean isElementIndex(int index) {
        return index >= 0 && index < size;
    }

    //判断位置合法性,用于迭代器或add操作
    private boolean isPositionIndex(int index) {
        return index >= 0 && index <= size;
    }

    //抛出的异常的详情
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }

    //检查链表节点下标合法性,不合法则抛出异常
    private void checkElementIndex(int index) {
        if (!isElementIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    //检查位置合法性,不合法则抛出异常
    private void checkPositionIndex(int index) {
        if (!isPositionIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(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;
        }
    }

    // 获得指定元素在链表第一次出现的下标,不存在返回-1
    public int indexOf(Object o) {
        int index = 0;
        //根据指定元素是否为null采取不同比较方式,加快比较
        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;
    }

    // 获得指定元素在链表最后一次出现的下标,不存在返回-1,类比indexOf
    public int lastIndexOf(Object o) {
        int index = size;
        if (o == null) {
            for (Node<E> x = last; x != null; x = x.prev) {
                index--;
                if (x.item == null)
                    return index;
            }
        } else {
            for (Node<E> x = last; x != null; x = x.prev) {
                index--;
                if (o.equals(x.item))
                    return index;
            }
        }
        return -1;
    }

    // 队列操作,获取表头节点的值,表头为空返回null
    public E peek() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
    }

    // 队列操作,获取表头节点的值,表头为空抛出异常
    public E element() {
        return getFirst();
    }

    // 队列操作,获取表头节点的值,并删除表头节点,表头为空返回null
    public E poll() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

    // 队列操作,获取表头节点的值,并删除表头节点,表头为空抛出异常
    public E remove() {
        return removeFirst();
    }

    // 队列操作,将指定的元素添加为此列表的尾部(最后一个元素)。
    public boolean offer(E e) {
        return add(e);
    }

    // 双向队列操作,链表首部插入新节点
    public boolean offerFirst(E e) {
        addFirst(e);
        return true;
    }

    // 双向队列操作,链表尾部插入新节点
    public boolean offerLast(E e) {
        addLast(e);
        return true;
    }

    // 双向队列操作,获取链表头节点值
    public E peekFirst() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
    }

    // 双向队列操作,获取尾节点值
    public E peekLast() {
        final Node<E> l = last;
        return (l == null) ? null : l.item;
    }

    // 双向队列操作,获取表头节点的值,并删除表头节点,表头为空返回null
    public E pollFirst() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

    // 双向队列操作,获取表尾节点的值,并删除表尾节点,表尾为空返回null
    public E pollLast() {
        final Node<E> l = last;
        return (l == null) ? null : unlinkLast(l);
    }

    //添加元素到表头
    public void push(E e) {
        addFirst(e);
    }

    // 删除并返回表头结点,为空则抛出异常
    public E pop() {
        return removeFirst();
    }

    // 删除在链表首次出现的指定元素
    public boolean removeFirstOccurrence(Object o) {
        return remove(o);
    }

    // 删除在链表最后一次出现的指定元素,类似remove()的实现
    public boolean removeLastOccurrence(Object o) {
        if (o == null) {
            for (Node<E> x = last; x != null; x = x.prev) {
                if (x.item == null) {
                    unlink(x);
                    return true;
                }
            }
        } else {
            for (Node<E> x = last; x != null; x = x.prev) {
                if (o.equals(x.item)) {
                    unlink(x);
                    return true;
                }
            }
        }
        return false;
    }

    // 返回从指定位置开始的ListIterator迭代器
    public ListIterator<E> listIterator(int index) {
        checkPositionIndex(index);  //检查位置合法性
        return new ListItr(index);
    }

    // ListItr的实现,支持双向
    private class ListItr implements ListIterator<E> {
        private Node<E> lastReturned = null;
        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();
        }
    }

    //节点实现
    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;
        }
    }

    // 返回一个迭代器在此双端队列以逆向顺序的元素
    public Iterator<E> descendingIterator() {
        return new DescendingIterator();
    }

    // DescendingIterator的实现,从后往前的迭代
    private class DescendingIterator implements Iterator<E> {
        private final ListItr itr = new ListItr(size());    //获得链表尾部的ListItr
        public boolean hasNext() {
            return itr.hasPrevious();
        }
        public E next() {
            return itr.previous();
        }
        public void remove() {
            itr.remove();
        }
    }

    @SuppressWarnings("unchecked")
    private LinkedList<E> superClone() {
        try {
            return (LinkedList<E>) super.clone();
        } catch (CloneNotSupportedException e) {
            throw new InternalError(e);
        }
    }

    //返回副本,浅拷贝,与ArrayList.clone()相似
    public Object clone() {
        LinkedList<E> clone = superClone(); //将clone构造成一个空的双向循环链表

        // Put clone into "virgin" state
        clone.first = clone.last = null;
        clone.size = 0;
        clone.modCount = 0;

        // Initialize clone with our elements
        for (Node<E> x = first; x != null; x = x.next)
            clone.add(x.item);  //浅拷贝,节点还是同一份引用

        return clone;
    }

    //返回一个包含此列表中所有元素的数组
    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;
    }

    //返回一个数组,使用运行时确定类型,该数组包含在这个列表中的所有元素(从第一到最后一个元素)
    //如果参数数组容量比链表节点数少,则返回链表数组;否则覆盖参数数组前size位,且第size位赋null,剩余不变。
    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        //如果参数数组容量不够,则重新申请容量足够的数组
        if (a.length < size)
            a = (T[])java.lang.reflect.Array.newInstance(
                    a.getClass().getComponentType(), size);
        int i = 0;
        Object[] result = a;
        //遍历依次覆盖
        for (Node<E> x = first; x != null; x = x.next)
            result[i++] = x.item;

        if (a.length > size)
            a[size] = null;

        return a;
    }

    private static final long serialVersionUID = 876323262645176354L;

    //保存链表实例的状态到一个流(即它序列化)。
    private void writeObject(java.io.ObjectOutputStream s)
            throws java.io.IOException {
        // Write out any hidden serialization magic
        s.defaultWriteObject();

        // 写入容量大小
        s.writeInt(size);

        // 按顺序写入链表元素
        for (Node<E> x = first; x != null; x = x.next)
            s.writeObject(x.item);
    }

    // 读操作,跟上述写操作类似
    @SuppressWarnings("unchecked")
    private void readObject(java.io.ObjectInputStream s)
            throws java.io.IOException, ClassNotFoundException {
        // Read in any hidden serialization magic
        s.defaultReadObject();

        // Read in size
        int size = s.readInt();

        // Read in all elements in the proper order.
        for (int i = 0; i < size; i++)
            linkLast((E)s.readObject());
    }

    // 返回Spliterator迭代器,可用于多线程,java8新增
    @Override
    public Spliterator<E> spliterator() {
        return new LLSpliterator<E>(this, -1, 0);
    }

    // LLSpliterator实现 ,类似ArrayList.ArrayListSpliterator,之后学习完善
    static final class LLSpliterator<E> implements Spliterator<E> {
        static final int BATCH_UNIT = 1 << 10;  // batch array size increment
        static final int MAX_BATCH = 1 << 25;  // max batch array size;
        final LinkedList<E> list; // null OK unless traversed
        Node<E> current;      // current node; null until initialized
        int est;              // size estimate; -1 until first needed
        int expectedModCount; // initialized when est set
        int batch;            // batch size for splits

        LLSpliterator(LinkedList<E> list, int est, int expectedModCount) {
            this.list = list;
            this.est = est;
            this.expectedModCount = expectedModCount;
        }

        final int getEst() {
            int s; // force initialization
            final LinkedList<E> lst;
            if ((s = est) < 0) {
                if ((lst = list) == null)
                    s = est = 0;
                else {
                    expectedModCount = lst.modCount;
                    current = lst.first;
                    s = est = lst.size;
                }
            }
            return s;
        }

        public long estimateSize() { return (long) getEst(); }

        public Spliterator<E> trySplit() {
            Node<E> p;
            int s = getEst();
            if (s > 1 && (p = current) != null) {
                int n = batch + BATCH_UNIT;
                if (n > s)
                    n = s;
                if (n > MAX_BATCH)
                    n = MAX_BATCH;
                Object[] a = new Object[n];
                int j = 0;
                do { a[j++] = p.item; } while ((p = p.next) != null && j < n);
                current = p;
                batch = j;
                est = s - j;
                return Spliterators.spliterator(a, 0, j, Spliterator.ORDERED);
            }
            return null;
        }

        public void forEachRemaining(Consumer<? super E> action) {
            Node<E> p; int n;
            if (action == null) throw new NullPointerException();
            if ((n = getEst()) > 0 && (p = current) != null) {
                current = null;
                est = 0;
                do {
                    E e = p.item;
                    p = p.next;
                    action.accept(e);
                } while (p != null && --n > 0);
            }
            if (list.modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }

        public boolean tryAdvance(Consumer<? super E> action) {
            Node<E> p;
            if (action == null) throw new NullPointerException();
            if (getEst() > 0 && (p = current) != null) {
                --est;
                E e = p.item;
                current = p.next;
                action.accept(e);
                if (list.modCount != expectedModCount)
                    throw new ConcurrentModificationException();
                return true;
            }
            return false;
        }

        public int characteristics() {
            return Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值