LinkedList是用链表结构存储数据的,很适合数据的动态插入和删除,随机访问和遍历速度比较慢。另外,他还提供了List接口中没有定义的方法,专门用于操作表头和表尾元素,可以当作堆栈、队列和双向队列使用。
image.png

  1. 继承了AbstractSequentialList抽象类:在遍历LinkedList的时候,官方更推荐使用顺序访问,也就是使用我们的迭代器。(因为LinkedList底层是通过一个链表来实现的)(虽然LinkedList也提供了get(int index)方法,但是底层的实现是:每次调用get(int index)方法的时候,都需要从链表的头部或者尾部进行遍历,每一的遍历时间复杂度是O(index),而相对比ArrayList的底层实现,每次遍历的时间复杂度都是O(1)。所以不推荐通过get(int index)遍历LinkedList。至于上面的说从链表的头部后尾部进行遍历:官方源码对遍历进行了优化:通过判断索引index更靠近链表的头部还是尾部来选择遍历的方向)(所以这里遍历LinkedList推荐使用迭代器)。
  2. 实现了List接口。(提供List接口中所有方法的实现)
  3. 实现了Cloneable接口,它支持克隆(浅克隆),底层实现:LinkedList节点并没有被克隆,只是通过Object的clone()方法得到的Object对象强制转化为了LinkedList,然后把它内部的实例域都置空,然后把被拷贝的LinkedList节点中的每一个值都拷贝到clone中。
  4. 实现了Deque接口。实现了Deque所有的可选的操作。
  5. 实现了Serializable接口。表明它支持序列化。(和ArrayList一样,底层都提供了两个方法:readObject(ObjectInputStream o)、writeObject(ObjectOutputStream o),用于实现序列化,底层只序列化节点的个数和节点的值)。


    源码解释

    ```java public class LinkedListextends AbstractSequentialList implements List, Deque, Cloneable, java.io.Serializable { transient int size = 0; //LinkedList中存放的元素个数

    transient Node first; //头节点

    transient Node last; //尾节点

    //构造方法,创建一个空的列表 public LinkedList() { }

    //将一个指定的集合添加到LinkedList中,先完成初始化,在调用添加操作 public LinkedList(Collection<? extends E> c) {

    1. this();
    2. addAll(c);

    }

    //插入头节点 private void linkFirst(E e) {

     final Node<E> f = first;  //将头节点赋值给f节点
     //new 一个新的节点,此节点的data = e , pre = null , next - > f 
     final Node<E> newNode = new Node<>(null, e, f);
     first = newNode; //将新创建的节点地址复制给first
     if (f == null)  //f == null,表示此时LinkedList为空
         last = newNode;  //将新创建的节点赋值给last
     else
         f.prev = newNode;  //否则f.前驱指向newNode
     size++;
     modCount++;
    

    }

    //插入尾节点 void linkLast(E e) {

     final Node<E> l = last; 
     final Node<E> newNode = new Node<>(l, e, null);
     last = newNode;
     if (l == null)
         first = newNode;
     else
         l.next = newNode;
     size++;
     modCount++;
    

    }

    //在succ节点前插入e节点,并修改各个节点之间的前驱后继 void linkBefore(E e, Node succ) {

     // assert succ != null;
     final Node<E> pred = succ.prev;
     final Node<E> newNode = new Node<>(pred, e, succ);
     succ.prev = newNode;
     if (pred == null)
         first = newNode;
     else
         pred.next = newNode;
     size++;
     modCount++;
    

    }

    //删除头节点 private E unlinkFirst(Node f) {

     // assert f == first && f != null;
     final E element = f.item;
     final Node<E> next = f.next;
     f.item = null;
     f.next = null; // help GC
     first = next;
     if (next == null)
         last = null;
     else
         next.prev = null;
     size--;
     modCount++;
     return element;
    

    }

    //删除尾节点 private E unlinkLast(Node l) {

     // assert l == last && l != null;
     final E element = l.item;
     final Node<E> prev = l.prev;
     l.item = null;
     l.prev = null; // help GC
     last = prev;
     if (prev == null)
         first = null;
     else
         prev.next = null;
     size--;
     modCount++;
     return element;
    

    }

    //删除指定节点 E unlink(Node x) {

     // assert x != null;
     final E element = x.item;
     final Node<E> next = x.next;  //获取指定节点的前驱
     final Node<E> prev = x.prev;  //获取指定节点的后继
    
     if (prev == null) {
         first = next;   //如果前驱为null, 说明此节点为头节点
     } else {
         prev.next = next;  //前驱结点的后继节点指向当前节点的后继节点
         x.prev = null;     //当前节点的前驱置空
     }
    
     if (next == null) {    //如果当前节点的后继节点为null ,说明此节点为尾节点
         last = prev;
     } else {
         next.prev = prev;  //当前节点的后继节点的前驱指向当前节点的前驱节点
         x.next = null;     //当前节点的后继置空
     }
    
     x.item = null;     //当前节点的元素设置为null ,等待垃圾回收
     size--;
     modCount++;
     return element;
    

    }

    //获取LinkedList中的第一个节点信息 public E getFirst() {

     final Node<E> f = first;
     if (f == null)
         throw new NoSuchElementException();
     return f.item;
    

    }

    //获取LinkedList中的最后一个节点信息 public E getLast() {

     final Node<E> l = last;
     if (l == null)
         throw new NoSuchElementException();
     return l.item;
    

    }

    //删除头节点 public E removeFirst() {

     final Node<E> f = first;
     if (f == null)
         throw new NoSuchElementException();
     return unlinkFirst(f);
    

    }

    //删除尾节点 public E removeLast() {

     final Node<E> l = last;
     if (l == null)
         throw new NoSuchElementException();
     return unlinkLast(l);
    

    }

    //将添加的元素设置为LinkedList的头节点 public void addFirst(E e) {

     linkFirst(e);
    

    }

    //将添加的元素设置为LinkedList的尾节点 public void addLast(E e) {

     linkLast(e);
    

    }

    //判断LinkedList是否包含指定的元素 public boolean contains(Object o) {

     return indexOf(o) != -1;
    

    }

    //返回List中元素的数量 public int size() {

     return size;
    

    }

    //在LinkedList的尾部添加元素 public boolean add(E e) {

     linkLast(e);
     return true;
    

    }

    //删除指定的元素 public boolean remove(Object o) {

     if (o == null) {
         for (Node<E> x = first; x != null; x = x.next) {
             if (x.item == null) {
                 unlink(x);
                 return true;
             }
         }
     } else {
         for (Node<E> x = first; x != null; x = x.next) {
             if (o.equals(x.item)) {
                 unlink(x);
                 return true;
             }
         }
     }
     return false;
    

    }

    //将集合中的元素添加到List中 public boolean addAll(Collection<? extends E> c) {

     return addAll(size, c);
    

    }

    //将集合中的元素全部插入到List中,并从指定的位置开始 public boolean addAll(int index, Collection<? extends E> c) {

     checkPositionIndex(index);
    
     Object[] a = c.toArray();  //将集合转化为数组
     int numNew = a.length;  //获取集合中元素的数量
     if (numNew == 0)   //集合中没有元素,返回false
         return false;
    
     Node<E> pred, succ;
     if (index == size) {
         succ = null;
         pred = last;
     } else {
         succ = node(index); //获取位置为index的结点元素,并赋值给succ
         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;
    

    }

    //删除List中所有的元素 public void clear() {

     // 清除节点之间的所有链接是“不必要的”,但是:
     // - 如果丢弃的节点驻留在多个代中,则有助于分代GC
     // - 确保释放内存,即使存在可访问的迭代器
     for (Node<E> x = first; x != null; ) {
         Node<E> next = x.next;
         x.item = null;
         x.next = null;
         x.prev = null;
         x = next;
     }
     first = last = null;
     size = 0;
     modCount++;
    

    }

//获取指定位置的元素
public E get(int index) {
    checkElementIndex(index);
    return node(index).item;
}

//将节点防止在指定的位置
public E set(int index, E element) {
    checkElementIndex(index);
    Node<E> x = node(index);
    E oldVal = x.item;
    x.item = element;
    return oldVal;
}

//将节点放置在指定的位置
public void add(int index, E element) {
    checkPositionIndex(index);

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

//删除指定位置的元素
public E remove(int index) {
    checkElementIndex(index);
    return unlink(node(index));
}

//判断索引是否合法
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));
}

//返回指定位置的节点信息
//LinkedList无法随机访问,只能通过遍历的方式找到相应的节点
//为了提高效率,当前位置首先和元素数量的中间位置开始判断,小于中间位置,
//从头节点开始遍历,大于中间位置从尾节点开始遍历
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;
    }
}

//返回第一次出现指定元素的位置
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;
}

//返回最后一次出现元素的位置
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;
}

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

//获取第一个元素
public E element() {
    return getFirst();
}

//弹出第一元素,并删除
public E poll() {
    final Node<E> f = first;
    return (f == null) ? null : unlinkFirst(f);
}

//删除第一个元素
public E remove() {
    return removeFirst();
}

//添加到尾部
public boolean offer(E e) {
    return add(e);
}

//添加到头部
public boolean offerFirst(E e) {
    addFirst(e);
    return true;
}

//插入到最后一个元素
public boolean offerLast(E e) {
    addLast(e);
    return true;
}
//队列操作
//尝试弹出第一个元素,但是不删除元素
public E peekFirst() {
    final Node<E> f = first;
    return (f == null) ? null : f.item;
 }
//队列操作
//尝试弹出最后一个元素,不删除
public E peekLast() {
    final Node<E> l = last;
    return (l == null) ? null : l.item;
}

//弹出第一个元素,并删除
public E pollFirst() {
    final Node<E> f = first;
    return (f == null) ? null : unlinkFirst(f);
}

//弹出最后一个元素,并删除
public E pollLast() {
    final Node<E> l = last;
    return (l == null) ? null : unlinkLast(l);
}

//如队列,添加到头部
public void push(E e) {
    addFirst(e);
}

//出队列删除第一个节点
public E pop() {
    return removeFirst();
}

//删除指定元素第一次出现的位置 public boolean removeFirstOccurrence(Object o) { return remove(o); }

//删除指定元素最后一次出现的位置
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;
}

//遍历方法
public ListIterator<E> listIterator(int index) {
    checkPositionIndex(index);
    return new ListItr(index);
}
//内部类,实现ListIterator接口
private class ListItr implements ListIterator<E> {
    private Node<E> lastReturned = null;
    private Node<E> next;
    private int nextIndex;
    private int expectedModCount = modCount;

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

    public boolean hasNext() {
        return nextIndex < size;
    }

    public E next() {
        checkForComodification();
        if (!hasNext())
            throw new NoSuchElementException();

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

    public boolean hasPrevious() {
        return nextIndex > 0;
    }

    public E previous() {
        checkForComodification();
        if (!hasPrevious())
            throw new NoSuchElementException();

        lastReturned = next = (next == null) ? last : next.prev;
        nextIndex--;
        return lastReturned.item;
    }

    public int nextIndex() {
        return nextIndex;
    }

    public int previousIndex() {
        return nextIndex - 1;
    }

    public void remove() {
        checkForComodification();
        if (lastReturned == null)
            throw new IllegalStateException();

        Node<E> lastNext = lastReturned.next;
        unlink(lastReturned);
        if (next == lastReturned)
            next = lastNext;
        else
            nextIndex--;
        lastReturned = null;
        expectedModCount++;
    }

    public void set(E e) {
        if (lastReturned == null)
            throw new IllegalStateException();
        checkForComodification();
        lastReturned.item = e;
    }

    public void add(E e) {
        checkForComodification();
        lastReturned = null;
        if (next == null)
            linkLast(e);
        else
            linkBefore(e, next);
        nextIndex++;
        expectedModCount++;
    }

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

/**
 * 适配器通过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();
    }
}

/**
 * 返回此{@code LinkedList}的浅层副本(元素本身不会被克隆。)
 *
 * @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;
}


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


@SuppressWarnings("unchecked")
public <T> T[] toArray(T[] a) {
    if (a.length < size)
        a = (T[])java.lang.reflect.Array.newInstance(
                            a.getClass().getComponentType(), size);
    int i = 0;
    Object[] result = a;
    for (Node<E> x = first; x != null; x = x.next)
        result[i++] = x.item;

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

    return a;
}

private static final long serialVersionUID = 876323262645176354L;

//将对象写入到输出流中
private void writeObject(java.io.ObjectOutputStream s)
    throws java.io.IOException {
    // Write out any hidden serialization magic
    s.defaultWriteObject();

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

//从输入流中将对象读出
@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());
}

}

<a name="XiiNA"></a>
# 构造方法
```java
LinkedList() 
LinkedList(Collection<? extends E> c)

LinkedList没有长度的概念,所以不存在容量不足的问题,因此不需要提供初始化大小的构造方法,因此值提供了两个方法,一个是无参构造方法,初始一个LinkedList对象,和将指定的集合元素转化为LinkedList构造方法。

查找元素

    public E getFirst() {
        final Node<E> f = first;
        if (f == null)
            throw new NoSuchElementException();
        return f.item;
    }

    public E getLast() {
        final Node<E> l = last;
        if (l == null)
            throw new NoSuchElementException();
        return l.item;
    }
    public E get(int index) {
        // 范围校验
        checkElementIndex(index);
        // node方法获取节点
        return node(index).item;
    }

LinkedList 除了提供通用的 get,因为其属性中含有 first 和 last 节点,也提供了 getFirst 和 getLast 方法。

添加方法

尾部添加

//尾部添加
public boolean add(E e) {
     linkLast(e);
     return true;
}

void linkLast(E e) {
     final Node<E> l = last;
    //构造新的节点,上一节点指向原来的last
     final Node<E> newNode = new Node<>(l, e, null);
     last = newNode;
     if (l == null)
         first = newNode;
     else
          l.next = newNode;
     size++;
    // 操作数自增
     modCount++;
}

添加方法默认是添加到LinkedList的尾部,首先将last指定的节点赋值给l节点,然后新建节点newNode ,此节点的前驱指向l节点,data = e , next = null , 并将新节点赋值给last节点,它成为了最后一个节点,根据当前List是否为空做出相应的操作。若不为空将l的后继指针修改为newNodw。 size +1 , modCount+1

中间添加

//对于中间添加,需要首先进行范围检查,即保证插入位置index在[0, size]之间,
//否则抛出数组越界异常IndexOutOfBoundsException。
public void add(int index, E element) {
    // 范围检查
    checkPositionIndex(index);
    if (index == size)
        linkLast(element);
    else
        linkBefore(element, node(index));
}

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

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

如果index == size,其实就是尾部插入,所以调用了linkLast。
如果index < size,中间插入的时候,需要分两步:

  1. node(int index)方法获取到index位置的元素succ
  2. linkBefore(E e, Node succ)将需要插入的元素element连接到succ后面

node方法是一个频繁被调用的方法,LinkedList 的很多操作都依赖于该方法查找到对应的元素。根据索引 index 获取元素时,因为双向链表的支持前后遍历,所以进行了位置判断,index < (size >> 1),与中间位置比较,靠前则前序遍历,否则后序遍历。

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

遍历逻辑很简单,循环到index上一个节点(后序则是下一个)位置,获取next(后序使用prev)返回index位置对应的节点Node对象succ。
LinkList(链表) - 图2
linkBefore和linkLast几乎完全一样,除了一个是添加到 last 节点后,一个是添加到 succ 节点后。

    void linkBefore(E e, Node<E> succ) {
        // assert succ != null;
        final Node<E> pred = succ.prev;
        final Node<E> newNode = new Node<>(pred, e, succ);
        succ.prev = newNode;
        if (pred == null)
            first = newNode;
        else
            pred.next = newNode;
        size++;
        modCount++;
    }

对于中间插入,如果index为0时,其实就是头部插入,这个时候比不用调用node方法去查找元素了,所以LinkedList也提供了一个addFirst(E e)方法。

    public void addFirst(E e) {
        linkFirst(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)
            last = newNode;
        else
            f.prev = newNode;
        size++;
        modCount++;
    }

批量插入

LinkedList提供尾部批量插入和中间批量插入,但内部实现其实都是调用的addAll(int index, Collection<? extends E> c)。

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

    public boolean addAll(int index, Collection<? extends E> c) {
        // 范围校验
        checkPositionIndex(index);
        Object[] a = c.toArray();
        int numNew = a.length;
        if (numNew == 0)
            return false;
        // succ是index位置元素,pred是index的前一个元素
        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;
    }

addAll(int index, Collection<? extends E> c)方法初一看,好像有些复杂,但明白其原理后,就变得清晰多了。链表插入就如同接水管,先从某一个位置断开水管,然后用接口连接上需要接入的部分。这个方法里,关键的是两个Node对象pred, 和 succ,succ 是index位置元素,pred是index的前一个元素(变动)。
特殊情况 index == size 时,即尾部插入,所以succ 就是null了,而 pred则为尾部节点last。
然后就是循环赋值了,在循环中构造node节点,类似于linkLast。
最后的是衔接处理,如果尾部插入的话,那pred就是尾部节点了(循环赋值时有pred = newNode处理),所以只需要指定last = pred。而中间插入,指明 pred.next = succ、succ.prev = pred即将index位置与新的前一个元素绑定到一起。

修改方法

对于LinkedList集合中元素的修改,需要先查找到该元素,然后更改其Node节点数据item即可。

    public E set(int index, E element) {
        // 范围检查
        checkElementIndex(index);
        // 获取index对应位置的Node对象
        Node<E> x = node(index);
        E oldVal = x.item;
        x.item = element;
        return oldVal;
    }

删除方法

public boolean remove(Object o) {
        if (o == null) {
            for (Node<E> x = first; x != null; x = x.next) {
                if (x.item == null) {
                    unlink(x);
                    return true;
                }
            }
        } else {
            for (Node<E> x = first; x != null; x = x.next) {
                if (o.equals(x.item)) {
                    unlink(x);
                    return true;
                }
            }
        }
        return false;
}

删除方法,先循环遍历列表,找到item == o 的节点,在调用unlink()方法删除。
整个unlink方法就是个标准的双向链表删除操作,三个节点prev,x,next,删除x 其实就是将 prev指向next,并next指向prev,只是其中多了一些特殊的判断。

    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;
        // 前一节点prev存在则将prev的下一节点指向next,不存在则当前移除节点其实就是头结点,next就是新的first
        if (prev == null) {
            first = next;
        } else {
            prev.next = next;
            x.prev = null;
        }
        // 下一节点next存在,则将next上一节点指向prev,不存在则说明当前移除的是未节点
        if (next == null) {
            last = prev;
        } else {
            next.prev = prev;
            x.next = null;
        }
        // 触发GC工作
        x.item = null;
        size--;
        // 操作计数器自增
        modCount++;
        return element;
    }

批量删除

在LinkedList类中,并没有removeAll方法,因为他未对其进行重写,而是使用了父类AbstractCollection的。

    public boolean removeAll(Collection<?> c) {
        Objects.requireNonNull(c);
        boolean modified = false;
        // 使用迭代器
        Iterator<?> it = iterator();
        while (it.hasNext()) {
            if (c.contains(it.next())) {
                it.remove();
                modified = true;
            }
        }
        return modified;
    }

removeAll的实现原理其实就是迭代删除,迭代器的获取方法iterator()在AbstractCollection类中只是个抽象方法,AbstractList类有其实现,但AbstractSequentialList类中覆写该方法。

    public Iterator<E> iterator() {
        return listIterator();
    }

iterator方法会调用listIterator(),这个方法实现在AbstractList类中,他调用了listIterator(int index)方法,但LinkedList重写了该方法,所以兜兜转转最终还是回到了LinkedList中。

    public ListIterator<E> listIterator(int index) {
        checkPositionIndex(index);
        //这里ListItr对象是LinkedList的内部类
        return new ListItr(index);
    }

ListItr在初始化的时候,会将操作计数器modCount赋值给expectedModCount,而之后的每次remove方法,都会校验expectedModCount与modCount是否相等,否则会抛出异常。
ListItr的remove方法,每次调用后,都将expectedModCount自增,已达到和unlink中modCount++的同步,从而使得modCount == expectedModCount 一直成立,这也是为什么我们循环删除LinkedList元素时需要使用其迭代器的remove方法。

        public void remove() {
            // 校验modCount
            checkForComodification();
            if (lastReturned == null)
                throw new IllegalStateException();

            Node<E> lastNext = lastReturned.next;
            // unlink删除节点逻辑,该方法中有modCount++;
            unlink(lastReturned);
            if (next == lastReturned)
                next = lastNext;
            else
                nextIndex--;
            lastReturned = null;
            // expectedModCount自增
            expectedModCount++;
        }

        final void checkForComodification() {
            // expectedModCount与modCount必须相等
            if (modCount != expectedModCount)
                throw new ConcurrentModificationException();
        }

使用场景

  • ArrayList,底层采用数组实现,如果需要遍历集合元素,应该使用随机访问的方式,对于LinkedList集合应该采用迭代器的方式
  • 如果需要经常的插入。删除操作可以考虑使用LinkedList集合
  • 如果有多个线程需要同时访问List集合中的元素,开发者可以考虑使用Collections将集合包装成线程安全的集合。

    总结

  1. LinkedList是双向链表实现的List
  2. LinkedList是非线程安全的
  3. LinkedList元素允许为null,允许重复元素
  4. LinkedList是基于链表实现的,因此插入删除效率高,查找效率低(虽然有一个加速动作)
  5. LinkedList是基于链表实现的,因此不存在容量不足的问题,所以没有扩容的方法
  6. LinkedList还实现了栈和队列的操作方法,因此也可以作为栈、队列和双端队列来使用