LinkedList

2015.01.16
                                                            By 

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 的成员。

start ->

声明

, 大家可以看看注释

/**
 * 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
 */

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

LinkedList. 属性

// 整个List有多少个结点
    // 第一个结点
    // 最后一个结点
    transient int size = 0;
    transient Node<E> first;
    transient Node<E> last;

LinkedList. LinkedList()

public LinkedList() {
}

public LinkedList(Collection<? extends E> c) {
    this();
    addAll(c);
}

LinkedList.add(E e)

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

LinkedList.linkLast(E e)
    void linkLast(E e) {
        final Node<E> l = last;
        // 新建一个结点 其prev为last 元素值为e next为null
        // 更新last
        // 如果插入结点之前没有元素 则设置first为新加入的结点
        // 否则设置之前的last结点的next为新加入的结点
        // 更新size, modeCount
        final Node<E> newNode = new Node<>(l, e, null);
        last = newNode;
        if (l == null)
            first = newNode;
        else
            l.next = newNode;
        size++;
        modCount++;
    }

12 java.util.LinkedList_java

LinkedList. add(int index, E element)

public void add(int index, E element) {
        // 校验index
        // 如果index为size, 则直接linkLast
        // 遍历到index处的结点, 并将ele连接到index处的结点之前
        checkPositionIndex(index);
        if (index == size)
            linkLast(element);
        else
            linkBefore(element, node(index));
    }

LinkedList. node(int index)
    Node<E> node(int index) {
        // assert isElementIndex(index);
        // 如果index<size/2  从first开始查找
        // 如果index>size/2  从last开始查找
        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;
        }
    }

LinkedList. linkBefore(E e, Node<E> succ)
    void linkBefore(E e, Node<E> succ) {
        // assert succ != null;
        // 找到succ的前一个结点
        // 创建一个结点 prev为succ的前一个结点 元素值为e next为succ
        // 设置succ的prev为新结点
        // 如果succ的前一个结点为null  更新first
            // 否则设置succ的前一个结点的next为新结点
        // 更新size, modCount
        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++;
    }

LinkedList. checkPositionIndex(int index)
    private void checkPositionIndex(int index) {
        if (!isPositionIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

LinkedList. isPositionIndex(int index)
private boolean isPositionIndex(int index) {
    // index>=0 并且index<=size 合法
        return index >= 0 && index <= size;
    }

12 java.util.LinkedList_结点_02

LinkedList.addFirst(E e)

public void addFirst(E e) {
        linkFirst(e);
    }

LinkedList. linkFirst(E e)
    private void linkFirst(E e) {
        final Node<E> f = first;
        // 新建一个结点prev为null 元素值为e next为first
        // 更新first结点
        // 如果插入e之前没有结点 则last为新加入的结点
        // 否则之前的first结点的prev为新加入的结点
        // 更新size, modCount
        final Node<E> newNode = new Node<>(null, e, f);
        first = newNode;
        if (f == null)
            last = newNode;
        else
            f.prev = newNode;
        size++;
        modCount++;
    }

12 java.util.LinkedList_java_03

LinkedList. addLast(E e)

public void addLast(E e) {
        linkLast(e);
    }

12 java.util.LinkedList_linkedlist_04

LinkedList.offer(E e)

public boolean offer(E e) {
        return add(e);
    }

LinkedList. offerFirst(E e)

public boolean offerFirst(E e) {
        addFirst(e);
        return true;
    }

LinkedList. offerLast(E e)

public boolean offerLast(E e) {
        addLast(e);
        return true;
    }

LinkedList. push(E e)

public void push(E e) {
        addFirst(e);
    }

LinkedList. addAll(Collection

public boolean addAll(Collection<? extends E> c) {
        return addAll(size, c);
    }

12 java.util.LinkedList_linkedlist_05

LinkedList. addAll(int index, Collection

public boolean addAll(int index, Collection<? extends E> c) {
    // 校验索引
        // succ是index处的结点
        // pred是index处结点的上一个结点, 我们的目的就是在pred和succ之间加入c中的所有元素
    // 将c中的所有元素链接到pred
    // 最后 链接pred之前的元素 和succ之后的元素
        // 如果pred为最后一个元素    更新last即可
            // 更新pred的next 和succ的prev
    // 更新size, modCount
        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 {
            succ = node(index);
            pred = succ.prev;
        }

        for (Object o : a) {
            @SuppressWarnings("unchecked") E e = (E) o;
            Node<E> newNode = new Node<>(pred, e, null);
            if (pred == null)
                first = newNode;
            else
                pred.next = newNode;
            pred = newNode;
        }
        if (succ == null) {
            last = pred;
        } else {
            pred.next = succ;
            succ.prev = pred;
        }

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

12 java.util.LinkedList_java_06

LinkedList. get(int index)

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

    private void checkElementIndex(int index) {
        if (!isElementIndex(index))
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

    private boolean isElementIndex(int index) {
        return index >= 0 && index < size;
    }

12 java.util.LinkedList_结点_07

LinkedList. getFirst()

public E getFirst() {
        final Node<E> f = first;
        // 如果当前list没有元素
        if (f == null)
            throw new NoSuchElementException();
        return f.item;
    }

LinkedList. getLast()

public E getLast() {
        final Node<E> l = last;
        // 如果当前list没有元素
        if (l == null)
            throw new NoSuchElementException();
        return l.item;
    }

LinkedList.element()

// 返回第一个元素(first)
    public E element() {
        return getFirst();
    }

LinkedList. indexOf(Object o)

public int indexOf(Object o) {
        int index = 0;
        // 从头开始依次遍历list 查找o
        // 如果o 为null, ==判定
            // 否则 equals判定

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

12 java.util.LinkedList_迭代器_08

LinkedList. lastIndexOf(Object o)

public int lastIndexOf(Object o) {
        int index = size;
        // 从后开始向前面遍历
        // 如果o是null  ==判定
            // 否则  equals判定
        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;
    }

12 java.util.LinkedList_java_09

LinkedList. contains(Object o)

public boolean contains(Object o) {
        return indexOf(o) != -1;
    }

LinkedList. peek()

// 返回第一个元素(first)
    public E peek() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
    }

LinkedList.peekFirst()

public E peekFirst() {
        final Node<E> f = first;
        return (f == null) ? null : f.item;
     }

LinkedList.peekLast()

public E peekLast() {
        final Node<E> l = last;
        return (l == null) ? null : l.item;
    }

LinkedList.pop()

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

LinkedList. set(int index, E element)

public E set(int index, E element) {
    // 校验索引
        // 更新index处结点的元素值
        checkElementIndex(index);
        Node<E> x = node(index);
        E oldVal = x.item;
        x.item = element;
        return oldVal;
    }

12 java.util.LinkedList_迭代器_10

LinkedList. remove(int index)

public E remove(int index) {
        // 校验index
        // 找到index处的结点 再unLink掉
        checkElementIndex(index);
        return unlink(node(index));
    }

LinkedList. unlink(Node<E> x)
    E unlink(Node<E> x) {
        // assert x != null;
        final E element = x.item;
        // 获取x的上一个结点以及下一个结点
        // 如果x是first结点, 重置first
            // 不是first结点    令上一个结点的next指向下一个结点 x的prev为清空
        // 如果x是last结点, 重置last
            // 如果不是last结点 令下一个结点的prev为上一个结点 将x的next清空
        // 清空x的元素值
        // 更新size, modCount
        final Node<E> next = x.next;
        final Node<E> prev = x.prev;
        if (prev == null) {
            first = next;
        } else {
            prev.next = next;
            x.prev = null;
        }
        if (next == null) {
            last = prev;
        } else {
            next.prev = prev;
            x.next = null;
        }
        x.item = null;
        size--;
        modCount++;
        return element;
    }

12 java.util.LinkedList_java_11

LinkedList. remove(Object o)

public boolean remove(Object o) {
        // 依次遍历list 查找o
        // o 为null
                // equals判定
        // 找到 并unlink掉
        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;
    }

LinkedList.removeFirst()

public E removeFirst() {
        final Node<E> f = first;
        // 如果first为null 抛出异常
        // unLinkFirst(f)
        if (f == null)
            throw new NoSuchElementException();
        return unlinkFirst(f);
    }

LinkedList. unlinkFirst(Node<E> f)
    private E unlinkFirst(Node<E> f) {
        // f必需为first
        // 将f结点的元素值 以及next引用清空
        // 令first为f的下一个结点
        // 如果f的下一个结点为null 说明此操作之前list中只有一个元  删除第一个元素之后last为null
            // 否则 令第二个结点的prev=null
        // 更新size, modCount
        // 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;
    }

LinkedList.removeLast()

public E removeLast() {
        final Node<E> l = last;
        // 如果last为null
        // unLinkLast(l)
        if (l == null)
            throw new NoSuchElementException();
        return unlinkLast(l);
    }

LinkedList. unlinkLast(Node<E> l)
    private E unlinkLast(Node<E> l) {
        // l必需为last
            // 获取倒数第二个结点 清空最后一个结点的数据
            // 更新last
            // 如果此list之前只有一个元素 令first为null
                // 否则令倒数第二个结点的next为null
        // 更新size, modCount
        // 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;
    }

LinkedList. removeFirstOccurrence(Object o)

public boolean removeFirstOccurrence(Object o) {
        return remove(o);
    }

LinkedList. removeLastOccurrence(Object o)

public boolean removeLastOccurrence(Object o) {
        // 从last开始遍历
        // 如果o为null  ==判定
            // 否则  equals判定
        // 找到该对象, unlink
        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;
    }

LinkedList.poll()

// 返回第一个元素(first) 并将其删除掉
    public E poll() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

LinkedList.pollFirst()

public E pollFirst() {
        final Node<E> f = first;
        return (f == null) ? null : unlinkFirst(f);
    }

LinkedList.pollLast()

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

LinkedList.size()

public int size() {
        return size;
    }

LinkedList.clear()

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
        // 清空整个列表的数据
        // 更新first, last, size
        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++;
    }

LinkedList. listIterator(int index)

public ListIterator<E> listIterator(int index) {
        checkPositionIndex(index);
        // 返回一个index处的迭代器
        return new ListItr(index);
    }

ListItr[InnerClass]

private class ListItr implements ListIterator<E> {
    // next, previous 上一次返回的元素, 下一个要返回的元素
    // 当前索引, expectedModCount为创建Iterator的时候的modCount
        private Node<E> lastReturned = null;
        private Node<E> next;
        private int nextIndex;
        private int expectedModCount = modCount;

        ListItr(int index) {
            // assert isPositionIndex(index);
            next = (index == size) ? null : node(index);
            nextIndex = index;
        }

        // 是否遍历到最后一个元素
        public boolean hasNext() {
            return nextIndex < size;
        }

        public E next() {
            // 并发修改检查
            // 更新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() {
            // 并发修改检查
            // 如果next==null  则遍历到最后一个元素之后了 previous返回last
            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() {
            // 并发修改检测
            // 如果刚 删掉/添加 一个元素 抛出非法状态异常
            // unLink正在遍历的元素
            // previous遍历时 next和lastReturned相同
            // next遍历是 next是lastReturned的下一个元素
            // 所以previous遍历删除元素的时候 不用修改nextIndex
            // 而next遍历删除元素的时候,要将next而next遍历删除元素的时候,要将nextIndex减一
            // 如果之前一次遍历是previous遍历
                // 如果是next遍历 删除该元素之后nextIndex减一
            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) {
            // 并发修改检测
            // 如果遍历到最后一个元素之后 将e添加到list最后
                // 否则链接到next之前
            checkForComodification();
            lastReturned = null;
            if (next == null)
                linkLast(e);
            else
                linkBefore(e, next);
            nextIndex++;
            expectedModCount++;
        }

        // 并发修改检查
        final void checkForComodification() {
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }
    }

LinkedList. descendingIterator()

public Iterator<E> descendingIterator() {
        return new DescendingIterator();
    }

DescendingIterator[InnerClass]

private class DescendingIterator implements Iterator<E> {
    // new一个ListItr 只是用previous遍历
        private final ListItr itr = new ListItr(size());
        public boolean hasNext() {
            return itr.hasPrevious();
        }
        public E next() {
            return itr.previous();
        }
        public void remove() {
            itr.remove();
        }
    }

LinkedList.clone()

public Object clone() {
        // 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;
    }

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

LinkedList.toArray()

public Object[] toArray() {
        // 新建一个Object数组
        // 添加所有的元素
        Object[] result = new Object[size];
        int i = 0;
        for (Node<E> x = first; x != null; x = x.next)
            result[i++] = x.item;
        return result;
    }

LinkedList. toArray(T[] a)

@SuppressWarnings("unchecked")
    public <T> T[] toArray(T[] a) {
    // 如果a的长度小于size  新建一个数组 长度为size
        // 这里没深复制 这是为什么??
        // 如果a的长度>size  令size以及之后的元素为null  用于检测数组的长度
        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;
    }

->

end, 其实就是一个链表表, 这里的实现, 是一个无头结点链表, 难点在于对于空链表场景的处理[添加元素之前为空链表, 或者删除元素之后为空节点], 以及双向迭代器