JDK1.8 LinkedList源码解析

ArrayList之后,记录一下阅读LinkedList源码的笔记。

还是有一些不太懂的地方,在代码中有标注,欢迎各位不吝赐教,感谢!

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不被持久化
    transient int size = 0;

    // 首节点
    transient Node<E> first;

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

    /**
     * 空构造函数
     */
    public LinkedList() {
    }

    /**
     * 根据Collection构造
     * @param  c Collection
     * @throws NullPointerException 当c==null时
     */
    public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }

    /**
     * 将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==null即队列之前没有元素
        if (f == null)
            // 最后一个节点即首节点
            last = newNode;
        else
            // 旧首节点的前一个为新节点
            f.prev = newNode;
        size++;
        modCount++;
    }

    /**
     * 将e连接到最后一个元素
     * 很多内容可以对比着LinkFirst看
     */
    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++;
    }

    /**
     * 将e插到非空节点succ前
     * 很多内容可以对比着LinkFirst看
     */
    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++;
    }

    /**
     * 删除非空头节点
     */
    private E unlinkFirst(Node<E> f) {
        // assert f == first && f != null;
        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;
    }

    /**
     * 删除最后一个非空节点
     */
    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
     */
    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;

        // x没有前驱节点
        if (prev == null) {
            // 头节点设为x的下一个节点
            first = next;
        } else {// x有前驱
            // 前驱节点的nect连接到x的nect
            prev.next = next;
            // x的prev置空
            x.prev = null;
        }// 实现没有节点的next连着x,x的prev也不连着任何节点

        // 逻辑同上
        if (next == null) {
            last = prev;
        } else {
            next.prev = prev;
            x.next = null;
        }// 实现没有节点的prev连着x,x的next也不连着任何节点

        x.item = null;
        size--;
        modCount++;
        return element;
    }

    /**
     * 返回列表的第一个元素
     *
     * @return
     * @throws NoSuchElementException 当列表为空时
     */
    public E getFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return f.item;
    }

    /**
     * 返回列表的最后一个元素
     *
     * @return
     * @throws NoSuchElementException 当列表为空时
     */
    public E getLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return l.item;
    }

    /**
     * 移除并返回列表第一个元素
     *
     * @return
     * @throws NoSuchElementException
     */
    public E removeFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
    }

    /**
     * 移除并返回最后一个元素
     *
     * @return
     * @throws NoSuchElementException
     */
    public E removeLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return unlinkLast(l);
    }

    /**
     * 将指定元素加到队首
     *
     * @param e 待添加元素
     */
    public void addFirst(E e) {
        linkFirst(e);
    }

    /**
     * 将指定元素加到队尾
     *
     * @param e
     */
    public void addLast(E e) {
        linkLast(e);
    }

    /**
     * 判断队列是否包含某元素
     *
     * @param o
     * @return {@code true}
     */
    public boolean contains(Object o) {
        return indexOf(o) != -1;
    }

    /**
     * 获取队列长度
     *
     * @return
     */
    public int size() {
        return size;
    }

    /**
     * 指定元素加到队尾
     *
     * @param e
     * @return
     */
    public boolean add(E e) {
        linkLast(e);
        return true;
    }

    /**
     * 删除队列中第一个等于指定对象的的元素
     *
     * @param o 待删除元素
     * @return {@code true} 当队列含有该元素时
     *         {@code false} 当队列没有该元素时
     */
    public boolean remove(Object o) {
        // 和ArrayList相同的逻辑,对空元素要分情况判断
        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;
    }

    /**
     * 添加Collection所有元素
     *
     * @param c collection
     * @return {@code true}
     * @throws NullPointerException
     */
    public boolean addAll(Collection<? extends E> c) {
        return addAll(size, c);
    }

    /**
     * 将Collection所有元素插入指定位置
     *
     * @param index 待插入位置
     * @param c collection
     * @return {@code true} 当成功调用时
     * @throws IndexOutOfBoundsException {@inheritDoc}
     * @throws NullPointerException 当Collection==null时
     */
    public boolean addAll(int index, Collection<? extends E> c) {
        // 检查index是否可以插入
        checkPositionIndex(index);

        // Collection转为数组
        Object[] a = c.toArray();
        int numNew = a.length;
        if (numNew == 0)
            return false;

        Node<E> pred, succ;
        // 若带插入位置是最后一个位置
        if (index == size) {
            succ = null;
            pred = last;// 将前指针指向当前最后元素
        } else {
            // 获取第index元素
            succ = node(index);
            pred = succ.prev;// 将前指针指向index位置的前一个元素
        }

        for (Object o : a) {
            @SuppressWarnings("unchecked") E e = (E) o;
            // 生成值为e,前指针为pred的节点
            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 {
            // 插入的最后一个元素的next借到succ上
            pred.next = succ;
            succ.prev = pred;
        }

        size += numNew;
        modCount++;
        return true;
    }

    /**
     * 清空所有元素
     * 好奇这部分内容的朋友可以去了解一下jvm的垃圾回收内容
     * 我的理解可能不到位,所以保留了源码注释,欢迎留言交流
     */
    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
        // 清除节点间连接不是必须的,但是:
        // 当被丢弃节点存活超过一代时,清除了连接有助于分代回收
        // 即使有可用迭代器时也确保会被清除

        // 不管是啥 置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++;
    }


    // Positional Access Operations

    /**
     * 获取第index个元素
     *
     * @param index
     * @return
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E get(int index) {
        // 先检查index是否在范围内
        checkElementIndex(index);
        return node(index).item;
    }

    /**
     * 替换第index个元素为指定element
     *
     * @param index
     * @param element
     * @return 被替换掉的元素
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E set(int index, E element) {
        // 检查
        checkElementIndex(index);
        Node<E> x = node(index);
        E oldVal = x.item;
        x.item = element;
        return oldVal;
    }

    /**
     * 插入指定元素到指定位置
     *
     * @param index
     * @param element
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public void add(int index, E element) {
        // 检查
        checkPositionIndex(index);

        if (index == size)// 插到队尾
            linkLast(element);
        else// 插到第index前
            linkBefore(element, node(index));
    }

    /**
     * 删除指定位置元素
     *
     * @param index
     * @return 被删除元素值
     * @throws IndexOutOfBoundsException {@inheritDoc}
     */
    public E remove(int index) {
        // 检查
        checkElementIndex(index);
        return unlink(node(index));
    }

    /**
     * 判断index位置上有没有元素
     * 注意和检查index位置是否在范围内不一样(isPositionIndex), index不可等于size, 第size个位置上是没有元素的
     */
    private boolean isElementIndex(int index) {
        return index >= 0 && index < size;
    }

    /**
     * 判断index位置是否适合迭代或执行添加操作
     * 即判断index是否在范围内,index可取size,第size个位置可以插入元素
     */
    private boolean isPositionIndex(int index) {
        return index >= 0 && index <= size;
    }

    /**
     * IndexOutOfBoundsException异常的详细信息
     */
    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }

    /**
     * 检查index是否有元素,无则抛出异常
     */
    private void checkElementIndex(int index) {
        if (!isElementIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    /**
     * 判断是否在范围内,当不在合适位置时抛出IndexOutOfBoundsException异常
      */
    private void checkPositionIndex(int index) {
        if (!isPositionIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    /**
     * 返回指定位置元素
     */
    Node<E> node(int index) {
        // assert isElementIndex(index);
        // 当index位于队列的前1/2时,从前向后遍历
        if (index < (size >> 1)) {
            Node<E> x = first;
            for (int i = 0; i < index; i++)
                x = x.next;
            return x;
        } else {// 当index位于队列的后1/2时,从后向前遍历
            Node<E> x = last;
            for (int i = size - 1; i > index; i--)
                x = x.prev;
            return x;
        }
    }

    // Search Operations

    /**
     * 返回指定元素o的索引
     * 返回的是第一个等于o的索引
     */
    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;
    }

    /**
     * 返回最后一个等于o的索引
     *
     */
    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;
    }

    // 实现Queue操作

    /**
     * 取队首值,但不删除该值
     * 链表为空时会返回null
     */
    public E peek() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
    }

    /**
     * 取队首值,但不删除该值
     *
     * @throws NoSuchElementException 链表为空时会抛出异常
     * @since 1.5
     */
    public E element() {
        return getFirst();
    }

    /**
     * 取队首值,并删除该元素
     * 链表为空时会返回null
     *
     */
    public E poll() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

    /**
     * 取队首值,并删除该元素
     *
     * @return
     * @throws NoSuchElementException 链表为空时会抛出异常
     * @since 1.5
     */
    public E remove() {
        return removeFirst();
    }

    /**
     * 指定元素加到队尾
     */
    public boolean offer(E e) {
        return add(e);
    }

    // 实现Deque操作
    /**
     * 指定元素加到队首
     *
     */
    public boolean offerFirst(E e) {
        addFirst(e);
        return true;
    }

    /**
     * 指定元素加到队尾
     *
     */
    public boolean offerLast(E e) {
        addLast(e);
        return true;
    }

    /**
     *  取队首值,但不删除该值
     *  链表为空时会返回null
     *
     */
    public E peekFirst() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
    }

    /**
     *  取队尾值,但不删除该值
     *  链表为空时会返回null
     */
    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);
    }

    /**
     * 删除并返回队首
     *
     *
     * @throws NoSuchElementException 当队列为空时
     * @since 1.6
     */
    public E pop() {
        return removeFirst();
    }

    /**
     * 删除第一个等于指定元值的元素
     *
     */
    public boolean removeFirstOccurrence(Object o) {
        return remove(o);
    }

    /**
     * 删除最后一个等于指定值的元素
     * 从后向前遍历
     */
    public boolean removeLastOccurrence(Object o) {
        // 对null分情况
        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;
    }

    /**
     * 返回从指定位置开始的链表迭代器
     * 符合{@code List.listIterator(int)}的约束
     *
     * 此迭代器有fail-fast特性: 当迭代器被创建后,如果不是通过迭代器的add和remove方法更改链表
     * 会抛出{@code ConcurrentModificationException}异常
     * 因此在并发修改的情况下,迭代器会立即抛错,这好过留存隐患
     *
     * @param index
     * @return
     * @throws IndexOutOfBoundsException {@inheritDoc}index不在范围内
     * @see List#listIterator(int) 实现List的listIterator(int)方法
     */
    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) {
            // 断言index位置有值
            next = (index == size) ? null : node(index);
            nextIndex = index;
        }

        // 判断有无下一个元素
        public boolean hasNext() {
            return nextIndex < size;
        }

        /**
         * 获取下一个元素值
         * @return
         */
        public E next() {
            // 检查有没有发生修改
            checkForComodification();
            // 判断有没有下一个值
            if (!hasNext())
                throw new NoSuchElementException();

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

        // 判断有没有前一个元素
        public boolean hasPrevious() {
            return nextIndex > 0;
        }

        /**
         * 获取前一个元素值
         * @return
         */
        public E previous() {
            // 检查有没有发生修改
            checkForComodification();
            // 判断有没有前一个元素
            if (!hasPrevious())
                throw new NoSuchElementException();
            // next为空,说明整个链表都遍历过,因此上一个遍历的元素应该是链表的尾
            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;
            // 调用LinkedList的方法,保持modCount和exceptModCount一致
            unlink(lastReturned);
            // 这个地方有点不懂,lastReturned经过unlink()之后已经被置为null
            // 为什么不直接==null,而且还执行lastReturned = null;
            // 就算是unlink()执行失败…为什么要判断是否相等呢(@_@;)
            // 看到这里的大佬们,请一定要留言赐教,感谢!!!
            if (next == lastReturned)
                next = lastNext;
            else
                nextIndex--;
            lastReturned = null;
            expectedModCount++;
        }

        /**
         * 设置值
         * @param e
         */
        public void set(E e) {
            if (lastReturned == null)
                throw new IllegalStateException();
            checkForComodification();
            lastReturned.item = e;
        }

        /**
         * 添加元素
         * @param e
         */
        public void add(E e) {
            // 检查是否发生修改
            checkForComodification();
            lastReturned = null;
            // 当链表已经遍历完,将e加到队尾
            if (next == null)
                linkLast(e);
            else // 否则加到next前
                linkBefore(e, next);
            nextIndex++;
            expectedModCount++;
        }

        /**
         * 遍历剩余元素,挨个执行Consumer的accept函数
         * @param action
         */
        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() {
            // modCount是LinkedList的修改计数,exceptedModCount是迭代器的修改计数
            // 值不相等说明有修改没有通过迭代器
            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;
        }
    }

    /**
     * 获取倒序迭代器
     * @since 1.6
     */
    public Iterator<E> descendingIterator() {
        return new DescendingIterator();
    }

    /**
     * 通过ListItr.previous实现倒序迭代器
     */
    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();
        }
    }

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

    /**
     * 浅复制
     *
     * @return a shallow copy of this {@code LinkedList} instance
     */
    public Object clone() {
        LinkedList<E> clone = superClone();

        // 创建
        clone.first = clone.last = null;
        clone.size = 0;
        clone.modCount = 0;

        // 初始化
        for (Node<E> x = first; x != null; x = x.next)
            clone.add(x.item);

        return clone;
    }

    /**
     * 按照从头到尾的顺序,转换成数组
     *
     * 调用者可随意更改数组值,不会影响链表,两个值储存在不同内存位置
     *
     * 是数组和集合转换的接口
     *
     * @return
     */
    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;
    }

    /**
     * 这段的源码注释很长,我说一下我理解了的…
     * 还是转换成数组,不过可以不用开辟新空间
     *
     * @param a
     * @return
     * @throws ArrayStoreException 当a的类型不是链表元素的父类时
     * @throws NullPointerException 当a==null时
     */
    @SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
        // 当空间不够大时,重新申请类型与a类型相同、大小等于size的数组
        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;

    /**
     * 序列化链表
     *
     * @serialData 序列化链表大小和各个元素
     */
    private void writeObject(java.io.ObjectOutputStream s)
            throws java.io.IOException {
        // Write out any hidden serialization magic
        s.defaultWriteObject();

        // Write out size
        s.writeInt(size);

        // Write out all elements in the proper order.
        for (Node<E> x = first; x != null; x = x.next)
            s.writeObject(x.item);
    }

    /**
     * 反序列化(deserializes),根据输入流重建对象
     */
    @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());
    }

    /**
     * 创建一个<em><a href="Spliterator.html#binding">late-binding</a></em>
     * 和<em>fail-fast</em> {@link Spliterator}的迭代器
     * 
     * 这个部分还是没怎么看懂,学习一下,之后更新
     *
     * <p>The {@code Spliterator} reports {@link Spliterator#SIZED} and
     * {@link Spliterator#ORDERED}.  Overriding implementations should document
     * the reporting of additional characteristic values.
     *
     * @implNote
     * The {@code Spliterator} additionally reports {@link Spliterator#SUBSIZED}
     * and implements {@code trySplit} to permit limited parallelism..
     *
     * @return a {@code Spliterator} over the elements in this list
     * @since 1.8
     */
    @Override
    public Spliterator<E> spliterator() {
        return new LLSpliterator<E>(this, -1, 0);
    }

    /** Spliterators.IteratorSpliterator的变体 */
    static final class LLSpliterator<E> implements Spliterator<E> {
        static final int BATCH_UNIT = 1 << 10;  // 批量数组增量大小
        static final int MAX_BATCH = 1 << 25;  // 批量数组最大量
        final LinkedList<E> list; // 遍历前为null
        Node<E> current;      // 当前节点,初始化前为null
        int est;              // 大小估算,第一次使用前为-1
        int expectedModCount; // 当est被赋值时,该值初始化
        int batch;            // 拆分的批量大小

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

}

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
编译原理是计算机专业的一门核心课程,旨在介绍编译程序构造的一般原理和基本方法。编译原理不仅是计算机科学理论的重要组成部分,也是实现高效、可靠的计算机程序设计的关键。本文将对编译原理的基本概念、发展历程、主要内容和实际应用进行详细介绍编译原理是计算机专业的一门核心课程,旨在介绍编译程序构造的一般原理和基本方法。编译原理不仅是计算机科学理论的重要组成部分,也是实现高效、可靠的计算机程序设计的关键。本文将对编译原理的基本概念、发展历程、主要内容和实际应用进行详细介绍编译原理是计算机专业的一门核心课程,旨在介绍编译程序构造的一般原理和基本方法。编译原理不仅是计算机科学理论的重要组成部分,也是实现高效、可靠的计算机程序设计的关键。本文将对编译原理的基本概念、发展历程、主要内容和实际应用进行详细介绍编译原理是计算机专业的一门核心课程,旨在介绍编译程序构造的一般原理和基本方法。编译原理不仅是计算机科学理论的重要组成部分,也是实现高效、可靠的计算机程序设计的关键。本文将对编译原理的基本概念、发展历程、主要内容和实际应用进行详细介绍编译原理是计算机专业的一门核心课程,旨在介绍编译程序构造的一般原理和基本

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值