LinkedList 源代码

来源:互联网 发布:弹幕源码 编辑:程序博客网 时间:2024/06/05 04:08

1、底层是用双链表实现的

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

2、在查找元素的代码有做优化

  /**     * Returns the (non-null) Node at the specified element index.     */    Node<E> node(int index) {        // assert isElementIndex(index);        //查找第index个元素,在这有做优化的        if (index < (size >> 1)) {            //如果index在中间元素的左边,则从头结点向尾结点扫描            Node<E> x = first;            for (int i = 0; i < index; i++)                x = x.next;            return x;        } else {            //如果index在中间元素的右边,则从尾结点向头结点扫描            Node<E> x = last;            for (int i = size - 1; i > index; i--)                x = x.prev;            return x;        }    }


3、源代码

父类AbstractSequentialList源代码

/* * Copyright (c) 1997, 2006, Oracle and/or its affiliates. All rights reserved. * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms. * * * * * * * * * * * * * * * * * * * * */package java.util;/** * This class provides a skeletal implementation of the <tt>List</tt> * interface to minimize the effort required to implement this interface * backed by a "sequential access" data store (such as a linked list).  For * random access data (such as an array), <tt>AbstractList</tt> should be used * in preference to this class.<p> * * This class is the opposite of the <tt>AbstractList</tt> class in the sense * that it implements the "random access" methods (<tt>get(int index)</tt>, * <tt>set(int index, E element)</tt>, <tt>add(int index, E element)</tt> and * <tt>remove(int index)</tt>) on top of the list's list iterator, instead of * the other way around.<p> * * To implement a list the programmer needs only to extend this class and * provide implementations for the <tt>listIterator</tt> and <tt>size</tt> * methods.  For an unmodifiable list, the programmer need only implement the * list iterator's <tt>hasNext</tt>, <tt>next</tt>, <tt>hasPrevious</tt>, * <tt>previous</tt> and <tt>index</tt> methods.<p> * * For a modifiable list the programmer should additionally implement the list * iterator's <tt>set</tt> method.  For a variable-size list the programmer * should additionally implement the list iterator's <tt>remove</tt> and * <tt>add</tt> methods.<p> * * The programmer should generally provide a void (no argument) and collection * constructor, as per the recommendation in the <tt>Collection</tt> interface * specification.<p> * * This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * * @author  Josh Bloch * @author  Neal Gafter * @see Collection * @see List * @see AbstractList * @see AbstractCollection * @since 1.2 *//*此类提供了 List 接口的骨干实现,从而最大限度地减少了实现受“连续访问”数据存储(如链接列表)支持的此接口所需的工作。对于随机访问数据(如数组),应该优先使用 AbstractList,而不是先使用此类。从某种意义上说,此类与在列表的列表迭代器上实现“随机访问”方法(get(int index)、set(int index, E element)、add(int index, E element) 和 remove(int index))的 AbstractList 类相对立,而不是其他关系。要实现一个列表,程序员只需要扩展此类,并提供 listIterator 和 size 方法的实现即可。对于不可修改的列表,程序员只需要实现列表迭代器的 hasNext、next、hasPrevious、previous 和 index 方法即可。对于可修改的列表,程序员应该再另外实现列表迭代器的 set 方法。对于可变大小的列表,程序员应该再另外实现列表迭代器的 remove 和 add 方法。按照 Collection 接口规范中的推荐,程序员通常应该提供一个 void(无参数)构造方法和 collection 构造方法。此类是 Java Collections Framework 的成员。 */public abstract class AbstractSequentialList<E> extends AbstractList<E> {    /**     * Sole constructor.  (For invocation by subclass constructors, typically     * implicit.)     */    protected AbstractSequentialList() {    }    /**     * Returns the element at the specified position in this list.     *     * <p>This implementation first gets a list iterator pointing to the     * indexed element (with <tt>listIterator(index)</tt>).  Then, it gets     * the element using <tt>ListIterator.next</tt> and returns it.     *     * @throws IndexOutOfBoundsException {@inheritDoc}     */    public E get(int index) {        try {            //获取迭代器,取出            return listIterator(index).next();        } catch (NoSuchElementException exc) {            throw new IndexOutOfBoundsException("Index: "+index);        }    }    /**     * Replaces the element at the specified position in this list with the     * specified element (optional operation).     *     * <p>This implementation first gets a list iterator pointing to the     * indexed element (with <tt>listIterator(index)</tt>).  Then, it gets     * the current element using <tt>ListIterator.next</tt> and replaces it     * with <tt>ListIterator.set</tt>.     *     * <p>Note that this implementation will throw an     * <tt>UnsupportedOperationException</tt> if the list iterator does not     * implement the <tt>set</tt> operation.     *     * @throws UnsupportedOperationException {@inheritDoc}     * @throws ClassCastException            {@inheritDoc}     * @throws NullPointerException          {@inheritDoc}     * @throws IllegalArgumentException      {@inheritDoc}     * @throws IndexOutOfBoundsException     {@inheritDoc}     */    public E set(int index, E element) {        try {            //在迭代器中替换            ListIterator<E> e = listIterator(index);            E oldVal = e.next();            e.set(element);            return oldVal;        } catch (NoSuchElementException exc) {            throw new IndexOutOfBoundsException("Index: "+index);        }    }    /**     * Inserts the specified element at the specified position in this list     * (optional operation).  Shifts the element currently at that position     * (if any) and any subsequent elements to the right (adds one to their     * indices).     *     * <p>This implementation first gets a list iterator pointing to the     * indexed element (with <tt>listIterator(index)</tt>).  Then, it     * inserts the specified element with <tt>ListIterator.add</tt>.     *     * <p>Note that this implementation will throw an     * <tt>UnsupportedOperationException</tt> if the list iterator does not     * implement the <tt>add</tt> operation.     *     * @throws UnsupportedOperationException {@inheritDoc}     * @throws ClassCastException            {@inheritDoc}     * @throws NullPointerException          {@inheritDoc}     * @throws IllegalArgumentException      {@inheritDoc}     * @throws IndexOutOfBoundsException     {@inheritDoc}     */    public void add(int index, E element) {        try {            //在迭代器添加            listIterator(index).add(element);        } catch (NoSuchElementException exc) {            throw new IndexOutOfBoundsException("Index: "+index);        }    }    /**     * Removes the element at the specified position in this list (optional     * operation).  Shifts any subsequent elements to the left (subtracts one     * from their indices).  Returns the element that was removed from the     * list.     *     * <p>This implementation first gets a list iterator pointing to the     * indexed element (with <tt>listIterator(index)</tt>).  Then, it removes     * the element with <tt>ListIterator.remove</tt>.     *     * <p>Note that this implementation will throw an     * <tt>UnsupportedOperationException</tt> if the list iterator does not     * implement the <tt>remove</tt> operation.     *     * @throws UnsupportedOperationException {@inheritDoc}     * @throws IndexOutOfBoundsException     {@inheritDoc}     */    public E remove(int index) {        try {            //获取迭代器            ListIterator<E> e = listIterator(index);            //remove之前需要先调用next来获取            E outCast = e.next();            e.remove();            return outCast;        } catch (NoSuchElementException exc) {            throw new IndexOutOfBoundsException("Index: "+index);        }    }    // Bulk Operations    /**     * Inserts all of the elements in the specified collection into this     * list at the specified position (optional operation).  Shifts the     * element currently at that position (if any) and any subsequent     * elements to the right (increases their indices).  The new elements     * will appear in this list in the order that they are returned by the     * specified collection's iterator.  The behavior of this operation is     * undefined if the specified collection is modified while the     * operation is in progress.  (Note that this will occur if the specified     * collection is this list, and it's nonempty.)     *     * <p>This implementation gets an iterator over the specified collection and     * a list iterator over this list pointing to the indexed element (with     * <tt>listIterator(index)</tt>).  Then, it iterates over the specified     * collection, inserting the elements obtained from the iterator into this     * list, one at a time, using <tt>ListIterator.add</tt> followed by     * <tt>ListIterator.next</tt> (to skip over the added element).     *     * <p>Note that this implementation will throw an     * <tt>UnsupportedOperationException</tt> if the list iterator returned by     * the <tt>listIterator</tt> method does not implement the <tt>add</tt>     * operation.     *     * @throws UnsupportedOperationException {@inheritDoc}     * @throws ClassCastException            {@inheritDoc}     * @throws NullPointerException          {@inheritDoc}     * @throws IllegalArgumentException      {@inheritDoc}     * @throws IndexOutOfBoundsException     {@inheritDoc}     */    public boolean addAll(int index, Collection<? extends E> c) {        try {            boolean modified = false;            ListIterator<E> e1 = listIterator(index);            Iterator<? extends E> e2 = c.iterator();            //通过迭代器添加            while (e2.hasNext()) {                e1.add(e2.next());                modified = true;            }            return modified;        } catch (NoSuchElementException exc) {            throw new IndexOutOfBoundsException("Index: "+index);        }    }    // Iterators    /**     * Returns an iterator over the elements in this list (in proper     * sequence).<p>     *     * This implementation merely returns a list iterator over the list.     *     * @return an iterator over the elements in this list (in proper sequence)     */    public Iterator<E> iterator() {        return listIterator();    }    /**     * Returns a list iterator over the elements in this list (in proper     * sequence).     *     * @param  index index of first element to be returned from the list     *         iterator (by a call to the <code>next</code> method)     * @return a list iterator over the elements in this list (in proper     *         sequence)     * @throws IndexOutOfBoundsException {@inheritDoc}     */    public abstract ListIterator<E> listIterator(int index);}

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.function.Consumer;/** * Doubly-linked list implementation of the {@code List} and {@code Deque} * interfaces.  Implements all optional list operations, and permits all * elements (including {@code null}). * * <p>All of the operations perform as could be expected for a doubly-linked * list.  Operations that index into the list will traverse the list from * the beginning or the end, whichever is closer to the specified index. * * <p><strong>Note that this implementation is not synchronized.</strong> * If multiple threads access a linked list concurrently, and at least * one of the threads modifies the list structurally, it <i>must</i> be * synchronized externally.  (A structural modification is any operation * that adds or deletes one or more elements; merely setting the value of * an element is not a structural modification.)  This is typically * accomplished by synchronizing on some object that naturally * encapsulates the list. * * If no such object exists, the list should be "wrapped" using the * {@link Collections#synchronizedList Collections.synchronizedList} * method.  This is best done at creation time, to prevent accidental * unsynchronized access to the list:<pre> *   List list = Collections.synchronizedList(new LinkedList(...));</pre> * * <p>The iterators returned by this class's {@code iterator} and * {@code listIterator} methods are <i>fail-fast</i>: if the list is * structurally modified at any time after the iterator is created, in * any way except through the Iterator's own {@code remove} or * {@code add} methods, the iterator will throw a {@link * 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. * * <p>Note that the fail-fast behavior of an iterator cannot be guaranteed * as it is, generally speaking, impossible to make any hard guarantees in the * presence of unsynchronized concurrent modification.  Fail-fast iterators * throw {@code ConcurrentModificationException} on a best-effort basis. * Therefore, it would be wrong to write a program that depended on this * exception for its correctness:   <i>the fail-fast behavior of iterators * should be used only to detect bugs.</i> * * <p>This class is a member of the * <a href="{@docRoot}/../technotes/guides/collections/index.html"> * Java Collections Framework</a>. * * @author  Josh Bloch * @see     List * @see     ArrayList * @since 1.2 * @param <E> the type of elements held in this collection *//*List 接口的链接列表实现。实现所有可选的列表操作,并且允许所有元素(包括 null)。除了实现 List 接口外,LinkedList 类还为在列表的开头及结尾 get、remove 和 insert 元素提供了统一的命名方法。这些操作允许将链接列表用作堆栈、队列或双端队列。此类实现 Deque 接口,为 add、poll 提供先进先出队列操作,以及其他堆栈和双端队列操作。所有操作都是按照双重链接列表的需要执行的。在列表中编索引的操作将从开头或结尾遍历列表(从靠近指定索引的一端)。注意,此实现不是同步的。如果多个线程同时访问一个链接列表,而其中至少一个线程从结构上修改了该列表,则它必须 保持外部同步。(结构修改指添加或删除一个或多个元素的任何操作;仅设置元素的值不是结构修改。)这一般通过对自然封装该列表的对象进行同步操作来完成。如果不存在这样的对象,则应该使用Collections.synchronizedList 方法来“包装”该列表。最好在创建时完成这一操作,以防止对列表进行意外的不同步访问,如下所示:   List list = Collections.synchronizedList(new LinkedList(...));此类的 iterator 和   listIterator 方法返回的迭代器是快速失败 的:在迭代器创建之后,如果从结构上对列表进行修改,   除非通过迭代器自身的 remove 或 add 方法,其他任何时间任何方式的修改,迭代器都将抛出   ConcurrentModificationException。因此,面对并发的修改,迭代器很快就会完全失败,   而不冒将来不确定的时间任意发生不确定行为的风险。注意,迭代器的快速失败行为不能得到保证,一般来说,存在不同步的并发修改时,不可能作出任何硬性保证。快速失败迭代器尽最大努力抛出 ConcurrentModificationException。因此,编写依赖于此异常的程序的方式是错误的,正确做法是:迭代器的快速失败行为应该仅用于检测程序错误。此类是 Java Collections Framework 的成员。 */public class LinkedList<E>    extends AbstractSequentialList<E>    implements List<E>, Deque<E>, Cloneable, java.io.Serializable{    //链表大小    transient int size = 0;    /**     * Pointer to first node.     * Invariant: (first == null && last == null) ||     *            (first.prev == null && first.item != null)     */    //链表第一个结点    transient Node<E> first;    /**     * Pointer to last node.     * Invariant: (first == null && last == null) ||     *            (last.next == null && last.item != null)     */    //链表最后一个结点    transient Node<E> last;    /**     * Constructs an empty list.     */    public LinkedList() {    }    /**     * Constructs a list containing the elements of the specified     * collection, in the order they are returned by the collection's     * iterator.     *     * @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);    }    /**     * Links e as first element.     */    //将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)            //说明链接e元素前链表为空            last = newNode;        else            //双链表,需要设置f的前驱            f.prev = newNode;        //容量加一        size++;        //每次修改动作都需要modCount++        modCount++;    }    /**     * Links e as last element.     */    //将e设为最后一个结点    void linkLast(E e) {        final Node<E> l = last;        final Node<E> newNode = new Node<>(l, e, null);        last = newNode;        if (l == null)            //链接e前为空链表            first = newNode;        else            //需要设置l的后驱,因为是双链表            l.next = newNode;        //容量加一        size++;        modCount++;    }    /**     * Inserts element e before non-null Node succ.     */    //在succ前插入结点e    void linkBefore(E e, Node<E> succ) {        // assert succ != null;        //获取succ前驱结点        final Node<E> pred = succ.prev;        //插入新结点        final Node<E> newNode = new Node<>(pred, e, succ);        //修改succ的前驱结点为newNode        succ.prev = newNode;        if (pred == null)            //如果succ前驱结点为空,说明newNode应该为头结点            first = newNode;        else            //修改前驱结点的后驱结点为newNode            pred.next = newNode;        //容量加一        size++;        modCount++;    }    /**     * Unlinks non-null first node f.     */    //解除头结点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;        f.next = null; // help GC        //头指针指向后驱结点        first = next;        if (next == null)            //后驱结点为空,说明链表为空了            last = null;        else            //修改后驱结点的前驱为null            next.prev = null;        //容量减一        size--;        modCount++;        return element;    }    /**     * Unlinks non-null last node l.     */    //解除尾结点l    private E unlinkLast(Node<E> l) {        // assert l == last && l != null;        //        final E element = l.item;        final Node<E> prev = l.prev;        //将结点的值跟前驱设为null        l.item = null;        l.prev = null; // help GC        last = prev;        if (prev == null)            //prev==null说明链表为空了            first = null;        else            //修改prev的后驱为null            prev.next = null;        //容量减一        size--;        modCount++;        return element;    }    /**     * Unlinks non-null node 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) {            //说明结点x为头结点,重新指头结点            first = next;        } else {            //将x前驱结点的next指向x的后驱结点            prev.next = next;            //x的前驱结点设为null            x.prev = null;        }        if (next == null) {            //说明结点x为尾结点,重新指尾结点            last = prev;        } else {            //将x的前驱指向x的前驱结点            next.prev = prev;            //将x的后驱结点设为null            x.next = null;        }        //值设为null        x.item = null;        //容量减一        size--;        modCount++;        return element;    }    /**     * Returns the first element in this list.     *     * @return the first element in this list     * @throws NoSuchElementException if this list is empty     */    //获取头结点元素    public E getFirst() {        final Node<E> f = first;        if (f == null)            throw new NoSuchElementException();        return f.item;    }    /**     * Returns the last element in this list.     *     * @return the last element in this list     * @throws NoSuchElementException if this list is empty     */    //获取尾结点元素    public E getLast() {        final Node<E> l = last;        if (l == null)            throw new NoSuchElementException();        return l.item;    }    /**     * Removes and returns the first element from this list.     *     * @return the first element from this list     * @throws NoSuchElementException if this list is empty     */    //移除头结点    public E removeFirst() {        final Node<E> f = first;        if (f == null)            throw new NoSuchElementException();        return unlinkFirst(f);    }    /**     * Removes and returns the last element from this list.     *     * @return the last element from this list     * @throws NoSuchElementException if this list is empty     */    //移除尾结点    public E removeLast() {        final Node<E> l = last;        if (l == null)            throw new NoSuchElementException();        return unlinkLast(l);    }    /**     * Inserts the specified element at the beginning of this list.     *     * @param e the element to add     */    //添加头结点    public void addFirst(E e) {        linkFirst(e);    }    /**     * Appends the specified element to the end of this list.     *     * <p>This method is equivalent to {@link #add}.     *     * @param e the element to add     */    //添加尾结点    public void addLast(E e) {        linkLast(e);    }    /**     * Returns {@code true} if this list contains the specified element.     * More formally, returns {@code true} if and only if this list contains     * at least one element {@code e} such that     * <tt>(o==null ? e==null : o.equals(e))</tt>.     *     * @param o element whose presence in this list is to be tested     * @return {@code true} if this list contains the specified element     */    //判断链表是否包含o    public boolean contains(Object o) {        return indexOf(o) != -1;    }    /**     * Returns the number of elements in this list.     *     * @return the number of elements in this list     */    //返回容量    public int size() {        return size;    }    /**     * Appends the specified element to the end of this list.     *     * <p>This method is equivalent to {@link #addLast}.     *     * @param e element to be appended to this list     * @return {@code true} (as specified by {@link Collection#add})     */    public boolean add(E e) {        //在链表后添加元素        linkLast(e);        return true;    }    /**     * Removes the first occurrence of the specified element from this list,     * if it is present.  If this list does not contain the element, it is     * unchanged.  More formally, removes the element with the lowest index     * {@code i} such that     * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>     * (if such an element exists).  Returns {@code true} if this list     * contained the specified element (or equivalently, if this list     * changed as a result of the call).     *     * @param o element to be removed from this list, if present     * @return {@code true} if this list contained the specified element     */    public boolean remove(Object o) {        if (o == null) {            //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;    }    /**     * Appends all of the elements in the specified collection to the end of     * this list, in the order that they are returned by the specified     * collection's iterator.  The behavior of this operation is undefined if     * the specified collection is modified while the operation is in     * progress.  (Note that this will occur if the specified collection is     * this list, and it's nonempty.)     *     * @param c collection containing elements to be added to this list     * @return {@code true} if this list changed as a result of the call     * @throws NullPointerException if the specified collection is null     */    public boolean addAll(Collection<? extends E> c) {        return addAll(size, c);    }    /**     * Inserts all of the elements in the specified collection into this     * list, starting at the specified position.  Shifts the element     * currently at that position (if any) and any subsequent elements to     * the right (increases their indices).  The new elements will appear     * in the list in the order that they are returned by the     * specified collection's iterator.     *     * @param index index at which to insert the first element     *              from the specified collection     * @param c collection containing elements to be added to this list     * @return {@code true} if this list changed as a result of the call     * @throws IndexOutOfBoundsException {@inheritDoc}     * @throws NullPointerException if the specified collection is null     */    public boolean addAll(int index, Collection<? extends E> c) {        //检测下标index是否越界        checkPositionIndex(index);        Object[] a = c.toArray();        int numNew = a.length;        if (numNew == 0)            return false;        Node<E> pred, succ;        if (index == size) {            //在尾结点后面添加            succ = null;            pred = last;        } else {            //获得第index个结点            succ = node(index);            //第index-1个结点;            pred = succ.prev;        }        //遍历将容器c中的元素添加到链表        for (Object o : a) {            @SuppressWarnings("unchecked") E e = (E) o;            Node<E> newNode = new Node<>(pred, e, null);            if (pred == null)                //newNode是头结点                first = newNode;            else                //将上一个结点的next指向新的结点                pred.next = newNode;            //下一次遍历,当前的结点就是上一个结点了            pred = newNode;        }        if (succ == null) {            //第index-1个结点是尾结点            last = pred;        } else {            //将原先链表index后面的元素重新接到链表            pred.next = succ;            succ.prev = pred;        }        //容量加一        size += numNew;        modCount++;        return true;    }    /**     * Removes all of the elements from this list.     * The list will be empty after this call returns.     */    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        //递归将node设为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        first = last = null;        size = 0;        modCount++;    }    // Positional Access Operations    /**     * Returns the element at the specified position in this list.     *     * @param index index of the element to return     * @return the element at the specified position in this list     * @throws IndexOutOfBoundsException {@inheritDoc}     */    public E get(int index) {        checkElementIndex(index);        //返回第index个结点的元素        return node(index).item;    }    /**     * Replaces the element at the specified position in this list with the     * specified element.     *     * @param index index of the element to replace     * @param element element to be stored at the specified position     * @return the element previously at the specified position     * @throws IndexOutOfBoundsException {@inheritDoc}     */    public E set(int index, E element) {        checkElementIndex(index);        //获取第index个结点        Node<E> x = node(index);        E oldVal = x.item;        //设置新的值        x.item = element;        //将旧结点返回        return oldVal;    }    /**     * Inserts the specified element at the specified position in this list.     * Shifts the element currently at that position (if any) and any     * subsequent elements to the right (adds one to their indices).     *     * @param index index at which the specified element is to be inserted     * @param element element to be inserted     * @throws IndexOutOfBoundsException {@inheritDoc}     */    public void add(int index, E element) {        checkPositionIndex(index);        if (index == size)            //在尾结点后面添加            linkLast(element);        else            //index前添加            linkBefore(element, node(index));    }    /**     * Removes the element at the specified position in this list.  Shifts any     * subsequent elements to the left (subtracts one from their indices).     * Returns the element that was removed from the list.     *     * @param index the index of the element to be removed     * @return the element previously at the specified position     * @throws IndexOutOfBoundsException {@inheritDoc}     */    public E remove(int index) {        checkElementIndex(index);        //先找出在index的结点后在移除        return unlink(node(index));    }    /**     * Tells if the argument is the index of an existing element.     */    //检测是否越界    private boolean isElementIndex(int index) {        return index >= 0 && index < size;    }    /**     * Tells if the argument is the index of a valid position for an     * iterator or an add operation.     */    //检测是否越界,用于迭代器和添加操作    private boolean isPositionIndex(int index) {        return index >= 0 && index <= size;    }    /**     * Constructs an IndexOutOfBoundsException detail message.     * Of the many possible refactorings of the error handling code,     * this "outlining" performs best with both server and client VMs.     */    //越界时抛出异常的信息    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));    }    /**     * Returns the (non-null) Node at the specified element index.     */    //返回第index个元素    Node<E> node(int index) {        // assert isElementIndex(index);        //查找第index个元素,在这有做优化的        if (index < (size >> 1)) {            //如果index在中间元素的左边,则从头结点向尾结点扫描            Node<E> x = first;            for (int i = 0; i < index; i++)                x = x.next;            return x;        } else {            //如果index在中间元素的右边,则从尾结点向头结点扫描            Node<E> x = last;            for (int i = size - 1; i > index; i--)                x = x.prev;            return x;        }    }    // Search Operations    /**     * Returns the index of the first occurrence of the specified element     * in this list, or -1 if this list does not contain the element.     * More formally, returns the lowest index {@code i} such that     * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,     * or -1 if there is no such index.     *     * @param o element to search for     * @return the index of the first occurrence of the specified element in     *         this list, or -1 if this list does not contain the element     */    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;    }    /**     * Returns the index of the last occurrence of the specified element     * in this list, or -1 if this list does not contain the element.     * More formally, returns the highest index {@code i} such that     * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>,     * or -1 if there is no such index.     *     * @param o element to search for     * @return the index of the last occurrence of the specified element in     *         this list, or -1 if this list does not contain the element     */    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.    /**     * Retrieves, but does not remove, the head (first element) of this list.     *     * @return the head of this list, or {@code null} if this list is empty     * @since 1.5     */    //取出头结点元素,但是没有删除头结点,如果没有的话不会抛出异常,返回null    public E peek() {        final Node<E> f = first;        return (f == null) ? null : f.item;    }    /**     * Retrieves, but does not remove, the head (first element) of this list.     *     * @return the head of this list     * @throws NoSuchElementException if this list is empty     * @since 1.5     */    //取出头结点,如果没有的话会抛出异常    public E element() {        return getFirst();    }    /**     * Retrieves and removes the head (first element) of this list.     *     * @return the head of this list, or {@code null} if this list is empty     * @since 1.5     */    public E poll() {        final Node<E> f = first;        return (f == null) ? null : unlinkFirst(f);    }    /**     * Retrieves and removes the head (first element) of this list.     *     * @return the head of this list     * @throws NoSuchElementException if this list is empty     * @since 1.5     */    //移除头结点    public E remove() {        return removeFirst();    }    /**     * Adds the specified element as the tail (last element) of this list.     *     * @param e the element to add     * @return {@code true} (as specified by {@link Queue#offer})     * @since 1.5     */    //在尾结点后面插入元素    public boolean offer(E e) {        return add(e);    }    // Deque operations    /**     * Inserts the specified element at the front of this list.     *     * @param e the element to insert     * @return {@code true} (as specified by {@link Deque#offerFirst})     * @since 1.6     */    //从头结点前面插入元素    public boolean offerFirst(E e) {        addFirst(e);        return true;    }    /**     * Inserts the specified element at the end of this list.     *     * @param e the element to insert     * @return {@code true} (as specified by {@link Deque#offerLast})     * @since 1.6     */    //从尾结点后面插入元素    public boolean offerLast(E e) {        addLast(e);        return true;    }    /**     * Retrieves, but does not remove, the first element of this list,     * or returns {@code null} if this list is empty.     *     * @return the first element of this list, or {@code null}     *         if this list is empty     * @since 1.6     */    //返回头结点,不删除    public E peekFirst() {        final Node<E> f = first;        return (f == null) ? null : f.item;     }    /**     * Retrieves, but does not remove, the last element of this list,     * or returns {@code null} if this list is empty.     *     * @return the last element of this list, or {@code null}     *         if this list is empty     * @since 1.6     */    //返回尾结点,不删除    public E peekLast() {        final Node<E> l = last;        return (l == null) ? null : l.item;    }    /**     * Retrieves and removes the first element of this list,     * or returns {@code null} if this list is empty.     *     * @return the first element of this list, or {@code null} if     *     this list is empty     * @since 1.6     */    //返回头结点,删除    public E pollFirst() {        final Node<E> f = first;        return (f == null) ? null : unlinkFirst(f);    }    /**     * Retrieves and removes the last element of this list,     * or returns {@code null} if this list is empty.     *     * @return the last element of this list, or {@code null} if     *     this list is empty     * @since 1.6     */    //返回尾结点,删除    public E pollLast() {        final Node<E> l = last;        return (l == null) ? null : unlinkLast(l);    }    /**     * Pushes an element onto the stack represented by this list.  In other     * words, inserts the element at the front of this list.     *     * <p>This method is equivalent to {@link #addFirst}.     *     * @param e the element to push     * @since 1.6     */    //从头结点前面插入元素    public void push(E e) {        addFirst(e);    }    /**     * Pops an element from the stack represented by this list.  In other     * words, removes and returns the first element of this list.     *     * <p>This method is equivalent to {@link #removeFirst()}.     *     * @return the element at the front of this list (which is the top     *         of the stack represented by this list)     * @throws NoSuchElementException if this list is empty     * @since 1.6     */    //返回头结点并移除    public E pop() {        return removeFirst();    }    /**     * Removes the first 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     */    //移除第一个在链表中出现的o    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     */    //移除最后一个出现o的结点    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)     */    //返回list迭代器    public ListIterator<E> listIterator(int index) {        checkPositionIndex(index);        return new ListItr(index);    }    private class ListItr implements ListIterator<E> {        //上次调用的结点        private Node<E> lastReturned = null;        //将要调用next方法的结点        private Node<E> next;        //将要调用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)                //上次调用是previous,则需要再设置next                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                //从next的前面插入结点                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        //先将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        //先读取size        int size = s.readInt();        // Read in all elements in the proper order.        //读取每个元素,调用linkLast来插入组成链表        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