JDK1.8源码解析-LinkedList

LinkedList源码解析

一封不动的源代码 + 注释

 

注意
poll()返回并删除头节点
remove()返回并删除头节点

offer(E e)添加元素到队列尾部
offerFirst( E e)插入指定元素到队列头部
offerLast( E e)插入指定元素到队列尾部

peekFirst()返回队列的头元素
peekLast()返回队列的尾元素

pollFirst()删除并返回队列的第一个元素,如果头节点为空,则返回null.
pollLast()删除并返回队列的最后个元素,如果尾节点为空,则返回null.
栈方法
push( E e)插入指定元素到栈头  =addfirst
pop()删除并返回栈头元素

LinkedList所有代码如下:



/*
 * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 */

package java.util;

import java.util.LinkedList.Node;
import java.util.function.Consumer;

/**
 * @author  Josh Bloch
 * @see     List
 * @see     ArrayList
 * @since 1.2
 * @param <E> the type of elements held in this collection
 
 LinkedList是List接口和Deque接口的双向链表实现。LinkedList实现了所有的列表操作,允许所有的元素(包括空元素)。
 所有的操作都是在对双向链表操作。
 LinkedList不是线程安全的。
 Collections.synchronizedList方法可以实现线程安全的操作。
 由iterator()和listIterator()返回的迭代器是fail-fast的。
 
 */
 
 /*
支持泛型 
AbstractSequentialList 只支持按次序访问 
DequeLinkedList可用作队列或双端队列 
clone可以调用clone()方法来返回实例的field-for-field拷贝 
Serializable:表明该类是可以序列化的。
 */
public class LinkedList<E>
    extends AbstractSequentialList<E>
    implements List<E>, Deque<E>, Cloneable, java.io.Serializable
{
	/**
	 * LinkedList节点个数
	 */
    transient int size = 0;

    /**
     * 指向头节点的指针
     * Invariant: (first == null && last == null) ||
     *            (first.prev == null && first.item != null)
     *  节点定义 补充
	    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;
	        }
	    }
     */
    transient Node<E> first;

    /**
     * 指向尾节点的指针
     * Invariant: (first == null && last == null) ||
     *            (last.next == null && last.item != null)
     */
    transient Node<E> last;

    /**
     * Constructs an empty list.
     */
    public LinkedList() {
    }

    /**
     * 根据指定集合c构造linkedList。先构造一个空linkedlist,在把指定集合c中的所有元素都添加到linkedList中。
     *
     * @param  c the collection whose elements are to be placed into this list
     * @throws NullPointerException if the specified collection is null
     */
    public LinkedList(Collection<? extends E> c) {
        this();
        addAll(c);
    }

    /**
     * 在表头添加元素
     */
    private void linkFirst(E e) {
        //使节点f指向原来的头结点
        final Node<E> f = first;
        //新建节点newNode,节点的前指针指向null,后指针原来的头节点
        final Node<E> newNode = new Node<>(null, e, f);
        //头指针指向新的头节点newNode 
        first = newNode;
        //如果原来的头结点为null,更新尾指针,否则使原来的头结点f的前置指针指向新的头结点newNode
        if (f == null)
            last = newNode;
        else
            f.prev = newNode;
        size++;
        modCount++;
    }

    /**
     * 在表尾插入指定元素e
     */
    void linkLast(E e) {
        //使节点l指向原来的尾结点
        final Node<E> l = last;
        //新建节点newNode,节点的前指针指向l,后指针为null
        final Node<E> newNode = new Node<>(l, e, null);
        //尾指针指向新的头节点newNode
        last = newNode;
        //如果原来的尾结点为null,更新头指针,否则使原来的尾结点l的后置指针指向新的头结点newNode
        if (l == null)
            first = newNode;
        else
            l.next = newNode;
        size++;
        modCount++;
    }

    /**
     * 在指定节点succ之前插入指定元素e。指定节点succ不能为null。
     */
    void linkBefore(E e, Node<E> succ) {
        // assert succ != null;
        //获得指定节点的前驱
        final Node<E> pred = succ.prev;
        //新建节点newNode,前置指针指向pred,后置指针指向succ
        final Node<E> newNode = new Node<>(pred, e, succ);
        //succ的前置指针指向newTouch
        succ.prev = newNode;
        //如果指定节点的前驱为null,将newTouch设为头节点。否则更新pred的后置节点
        if (pred == null)
            first = newNode;
        else
            pred.next = newNode;
        size++;
        modCount++;
    }

    /**
     * 删除头结点f,并返回头结点的值
     */
    private E unlinkFirst( Node<E> f) {
        // assert f == first && f != null;
        // 保存头结点的值
        final E element = f.item;
        // 保存头结点指向的下个节点
        final Node<E> next = f.next;
        //头结点的值置为null
        f.item = null;
        //头结点的后置指针指向null
        f.next = null; // help GC
        //将头结点置为next
        first = next;
        //如果next为null,将尾节点置为null,否则将next的后置指针指向null
        if (next == null)
            last = null;
        else
            next.prev = null;
        size--;
        modCount++;
        //返回被删除的头结点的值
        return element;
    }

    /**
     * 删除尾节点l.并返回尾节点的值
     */
    private E unlinkLast(Node<E> l) {
        // assert l == last && l != null;
        // 保存尾节点的值
        final E element = l.item;
        //获取新的尾节点prev
        final Node<E> prev = l.prev;
        //旧尾节点的值置为null
        l.item = null;
        //旧尾节点的后置指针指向null
        l.prev = null; // help GC
        //将新的尾节点置为prev
        last = prev;
        //如果新的尾节点为null,头结点置为null,否则将新的尾节点的后置指针指向null
        if (prev == null)
            first = null;
        else
            prev.next = null;
        size--;
        modCount++;
        //返回被删除的尾节点的值
        return element;
    }

    /**
     * 删除指定节点,返回指定元素的值
     */
    E unlink(Node<E> x) {
        // assert x != null;
        // 保存指定节点的值
        final E element = x.item;
        // 获取指定节点的下个节点next
        final Node<E> next = x.next;
        // 获取指定节点的下个节点prev
        final Node<E> prev = x.prev;
        //如果prev为null,那么next为新的头结点,否则将prev的后置指针指向next,x的前置指针指向null
        if (prev == null) {
            first = next;
        } else {
            prev.next = next;
            x.prev = null;
        }
        //如果next为null,那么prev为新的尾结点,否则将next的前置指针指向prev,x的后置指针指向null
        if (next == null) {
            last = prev;
        } else {
            next.prev = prev;
            x.next = null;
        }
        //x的值置为null
        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);
    }

    /**
     * 在表尾插入指定元素.
     * 
     * 该方法等价于add()
     *
     * @param e 插入的指定元素
     */ 
    public void addLast(E e) {
        linkLast(e);
    }

    /**
     * 判断链表是否包含指定对象o
     * @param o 指定对象
     * @return 是否包含指定对象
     */
    public boolean contains(Object o) {
        return indexOf(o) != -1;
    }

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

    /**
     * 在表尾插入指定元素.
     *
     * 该方法等价于addLast
     *
     * @param e 插入的指定元素
     * @return true
     */
    public boolean add(E e) {
        linkLast(e);
        return true;
    }

    /**
     * 正向遍历链表,删除出现的第一个值为指定对象的节点
     *
     * @param o 要删除的节点置
     * @return 如果o在链表中存在,返回true
     */
    public boolean remove(Object o) {
        //遍历链表,如果o为null,删除第一个值为null的节点,返回true。如果不为null,删除第一个值为o的节点。如果链表中存在o,就返回true。
        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;
    }

    /**
     * 插入指定集合到链尾
     *
     * @param c 指定集合
     * @return 如果链表改变,返回true
     * @throws NullPointerException 如果指定集合为null
     */
    public boolean addAll(Collection<? extends E> c) {
        return addAll(size, c);
    }

    /**
     * 插入指定集合到链尾的指定位置
     *
     * @param index 指定的插入位置
     * @param c 插入的指定集合
     * @return 如果链表改变,返回true
     * @throws IndexOutOfBoundsException 如果index<0或index>size
     * @throws NullPointerException 如果指定集合为null
     */
    public boolean addAll(int index, Collection<? extends E> c) {
        //检查插入的位置是否合法
        checkPositionIndex(index);

        Object[] a = c.toArray();
        int numNew = a.length;
        if (numNew == 0)
            return false;//如果c是空的话那么就返回false

        //定义两个节点指针,指向插入点前后的节点元素
        Node<E> pred, succ;
        if (index == size) {
            succ = null;
            pred = last;
        } else {
            succ = node(index);//详见L566
            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;//把前面节点指向newNode即可!
        }

        // 修改插入后的指针问题
        if (succ == null) {
            last = pred;
        } else {
            pred.next = succ;
            succ.prev = pred;
        }

        size += numNew;
        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++;
    }


    // Positional Access Operations 按位操作

    /**
     * 返回指定索引处的元素
     *
     * @param index 指定索引
     * @return 指定索引处的元素
     * @throws IndexOutOfBoundsException 如果索引index越界
     */
    public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
    }

    /**
     * 替换指定索引处的元素为指定元素element
     *
     * @param index 被替换的元素的索引
     * @param element 
     * @return 指定元素element
     * @throws IndexOutOfBoundsException 索引越界
     */
    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 索引越界
     */
    public void add(int index, E element) {
        checkPositionIndex(index);

        if (index == size)
            linkLast(element);
        else
            linkBefore(element, node(index));
    }

    /**
     * 删除指定索引处的元素
     *
     * @param 指定索引
     * @return 指定索引处的元素
     * @throws IndexOutOfBoundsException 索引越界
     */
    public E remove(int index) {
        checkElementIndex(index);
        return unlink(node(index));
    }

    /**
     * 返回索引是否越界
     */
    private boolean isElementIndex(int index) {
        return index >= 0 && index < size;
    }

    /**
     * 返回插入操作时给定的索引是否合法
     */
    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) {
        // 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;
        }
    }

    // Search Operations 查找操作

    /**
     * 正向遍历链表,返回指定元素第一次出现时的索引。如果元素没有出现,返回-1.
     * 
     * @param o 需要查找的元素
     * @return 指定元素第一次出现时的索引。如果元素没有出现,返回-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;
    }

    /**
     * 逆向遍历链表,返回指定元素第一次出现时的索引。如果元素没有出现,返回-1.
     * 
     * @param o 需要查找的元素
     * @return 指定元素第一次出现时的索引。如果元素没有出现,返回-1。
     */
    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 operations.

    /**
     * 返回头节点的元素,如果链表为空则返回null
     *
     * @return 返回头节点的元素,如果链表为空则返回null
     * @since 1.5
     */
    public E peek() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
    }

    /**
     * 获取表头节点的值,头节点为空抛出异常
     *
     * @return 获取表头节点的值
     * @throws NoSuchElementException 如果链表为空
     * @since 1.5
     */
    public E element() {
        return getFirst();
    }

    /**
     * 返回并删除头节点,如果链表为空则返回null
     *
     * @return 返回并删除头节点,如果链表为空则返回null
     * @since 1.5
     */
    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();
    }

    /**
     * 添加元素到队列尾部
     *
     * @param e 指定元素
     * @return 
     * @since 1.5
     */
    public boolean offer(E e) {
        return add(e);
    }

    // Deque operations 双向队列操作
    /**
     * 插入指定元素到队列头部.
     *
     * @param e 插入的元素
     * @return  true
     * @since 1.6
     */
    public boolean offerFirst(E e) {
        addFirst(e);
        return true;
    }

    /**
     * 插入指定元素到队列尾部.
     *
     * @param e 插入的元素
     * @return  true
     * @since 1.6
     */
    public boolean offerLast(E e) {
        addLast(e);
        return true;
    }

    /**
    * 返回队列的头元素,如果头节点为空则返回空
    *
    * @return 返回队列的头元素,如果头节点为空则返回空
    * @since 1.6
    */
    public E peekFirst() {
       final Node<E> f = first;
       return (f == null) ? null : f.item;
    }

    /**
    * 返回队列的尾元素,如果尾节点为空则返回空
    *
    * @return 返回队列的尾元素,如果尾节点为空则返回空
    * @since 1.6
    */
    public E peekLast() {
        final Node<E> l = last;
        return (l == null) ? null : l.item;
    }

    /**
     * 删除并返回队列的第一个元素,如果头节点为空,则返回null.
     *
     * @return 删除并返回队列的第一个元素,如果头节点为空,则返回null.
     * @since 1.6
     */
    public E pollFirst() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

    /**
     * 删除并返回队列的最后个元素,如果尾节点为空,则返回null.
     *
     * @return 删除并返回队列的最后一个元素,如果尾节点为空,则返回null.
     * @since 1.6
     */
    public E pollLast() {
        final Node<E> l = last;
        return (l == null) ? null : unlinkLast(l);
    }

    /**
     * 插入指定元素到栈头
     *
     * 此方法等价于addFirst(e)
     *
     * @param e 指定元素
     * @since 1.6
     */
    public void push(E e) {
        addFirst(e);
    }

    /**
     * 删除并返回栈头元素
     *
     * 此方法等价于pop()
     *
     * @return 返回栈头元素
     * @throws NoSuchElementException 如果栈为空
     * @since 1.6
     */
    public E pop() {
        return removeFirst();
    }

    /**
     * 正向遍历栈,删除指定对象第一次出现时,索引对应的元素
     * 
     * @param o 被删除的元素
     * @return true 如果元素出现
     * @since 1.6
     */
    public boolean removeFirstOccurrence(Object o) {
        return remove(o);
    }

    /**
     * Removes the last occurrence of the specified element in this
     * list (when traversing the list from head to tail).  If the list
     * does not contain the element, it is unchanged.
     *
     * @param o element to be removed from this list, if present
     * @return {@code true} if the list contained the specified element
     * @since 1.6
     */
    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;
    }

    /**
     * Returns a list-iterator of the elements in this list (in proper
     * sequence), starting at the specified position in the list.
     * Obeys the general contract of {@code List.listIterator(int)}.<p>
     *
     * The list-iterator is <i>fail-fast</i>: if the list is structurally
     * modified at any time after the Iterator is created, in any way except
     * through the list-iterator's own {@code remove} or {@code add}
     * methods, the list-iterator will throw a
     * {@code ConcurrentModificationException}.  Thus, in the face of
     * concurrent modification, the iterator fails quickly and cleanly, rather
     * than risking arbitrary, non-deterministic behavior at an undetermined
     * time in the future.
     *
     * @param index index of the first element to be returned from the
     *              list-iterator (by a call to {@code next})
     * @return a ListIterator of the elements in this list (in proper
     *         sequence), starting at the specified position in the list
     * @throws IndexOutOfBoundsException {@inheritDoc}
     * @see 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) {
            // 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;
        }
    }

    /**
     * @since 1.6
     */
    public Iterator<E> descendingIterator() {
        return new DescendingIterator();
    }

    /**
     * Adapter to provide descending iterators via 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);
        }
    }

    /**
     * Returns a shallow copy of this {@code LinkedList}. (The elements
     * themselves are not cloned.)
     *
     * @return a shallow copy of this {@code LinkedList} instance
     */
    public Object clone() {
        LinkedList<E> clone = superClone();

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

    /**
     * Returns an array containing all of the elements in this list
     * in proper sequence (from first to last element).
     *
     * <p>The returned array will be "safe" in that no references to it are
     * maintained by this list.  (In other words, this method must allocate
     * a new array).  The caller is thus free to modify the returned array.
     *
     * <p>This method acts as bridge between array-based and collection-based
     * APIs.
     *
     * @return an array containing all of the elements in this list
     *         in proper sequence
     */
    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;
    }

    /**
     * Returns an array containing all of the elements in this list in
     * proper sequence (from first to last element); the runtime type of
     * the returned array is that of the specified array.  If the list fits
     * in the specified array, it is returned therein.  Otherwise, a new
     * array is allocated with the runtime type of the specified array and
     * the size of this list.
     *
     * <p>If the list fits in the specified array with room to spare (i.e.,
     * the array has more elements than the list), the element in the array
     * immediately following the end of the list is set to {@code null}.
     * (This is useful in determining the length of the list <i>only</i> if
     * the caller knows that the list does not contain any null elements.)
     *
     * <p>Like the {@link #toArray()} method, this method acts as bridge between
     * array-based and collection-based APIs.  Further, this method allows
     * precise control over the runtime type of the output array, and may,
     * under certain circumstances, be used to save allocation costs.
     *
     * <p>Suppose {@code x} is a list known to contain only strings.
     * The following code can be used to dump the list into a newly
     * allocated array of {@code String}:
     *
     * <pre>
     *     String[] y = x.toArray(new String[0]);</pre>
     *
     * Note that {@code toArray(new Object[0])} is identical in function to
     * {@code toArray()}.
     *
     * @param a the array into which the elements of the list are to
     *          be stored, if it is big enough; otherwise, a new array of the
     *          same runtime type is allocated for this purpose.
     * @return an array containing the elements of the list
     * @throws ArrayStoreException if the runtime type of the specified array
     *         is not a supertype of the runtime type of every element in
     *         this list
     * @throws NullPointerException if the specified array is 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;

    /**
     * Saves the state of this {@code LinkedList} instance to a stream
     * (that is, serializes it).
     *
     * @serialData The size of the list (the number of elements it
     *             contains) is emitted (int), followed by all of its
     *             elements (each an Object) in the proper order.
     */
    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);
    }

    /**
     * Reconstitutes this {@code LinkedList} instance from a stream
     * (that is, deserializes it).
     */
    @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());
    }

    /**
     * Creates a <em><a href="Spliterator.html#binding">late-binding</a></em>
     * and <em>fail-fast</em> {@link Spliterator} over the elements in this
     * list.
     *
     * <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);
    }

    /** A customized variant of Spliterators.IteratorSpliterator */
    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;
        }
    }

}
















 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值