著作权归https://pdai.tech所有。 链接:https://pdai.tech/md/java/collection/java-collection-LinkedList.html

概述

LinkedList 同时实现了List 接口和 Deque 接口,也就是说它既可以看作一个顺序容器,又可以看作一个队列( Queue ),同时又可以看作一个栈(Stack)。这样看来,LinkedList简直就是个全能冠军。当你需要使用栈或者队列时,可以考虑使用LinkedList,一方面是因为 Java 官方已经声明不建议使用Stack类,更遗憾的是,Java 里根本没有一个叫做Queue 的类(它是个接口名字)。关于栈或队列,现在的首选是ArrayDeque,它有着比LinkedList (当作栈或队列使用时)有着更好的性能。
image.png
LinkedList的实现方式决定了所有跟下标相关的操作都是线性时间,而在首段或者末尾删除元素只需要常数时间。为追求效率LinkedList没有实现同步(synchronized),如果需要多个线程并发访问,可以先采用Collections.synchronizedList()方法对其进行包装。

LinkedLists实现

底层数据结构

LinkedList底层通过双向链表实现,本节将着重讲解插入和删除元素时双向链表的维护过程,也即是之间解跟List接口相关的函数,而将QueueStack以及Deque相关的知识放在下一节讲。双向链表的每个节点用内部类Node表示。LinkedList通过first和last引用分别指向链表的第一个和最后一个元素。注意这里没有所谓的哑元,当链表为空的时候first和last都指向null。

  1. transient int size = 0;
  2. /**
  3. * Pointer to first node.
  4. * Invariant: (first == null && last == null) ||
  5. * (first.prev == null && first.item != null)
  6. */
  7. transient Node<E> first;
  8. /**
  9. * Pointer to last node.
  10. * Invariant: (first == null && last == null) ||
  11. * (last.next == null && last.item != null)
  12. */
  13. transient Node<E> last;

其中Node是私有的内部类:

  1. private static class Node<E> {
  2. E item;
  3. Node<E> next;
  4. Node<E> prev;
  5. Node(Node<E> prev, E element, Node<E> next) {
  6. this.item = element;
  7. this.next = next;
  8. this.prev = prev;
  9. }
  10. }

构造函数

  1. /**
  2. * Constructs an empty list.
  3. */
  4. public LinkedList() {
  5. }
  6. /**
  7. * Constructs a list containing the elements of the specified
  8. * collection, in the order they are returned by the collection's
  9. * iterator.
  10. *
  11. * @param c the collection whose elements are to be placed into this list
  12. * @throws NullPointerException if the specified collection is null
  13. */
  14. public LinkedList(Collection<? extends E> c) {
  15. this();
  16. addAll(c);
  17. }

getFirst(), getLast()

获取第一个元素, 和获取最后一个元素:

  1. /**
  2. * Returns the first element in this list.
  3. *
  4. * @return the first element in this list
  5. * @throws NoSuchElementException if this list is empty
  6. */
  7. public E getFirst() {
  8. final Node<E> f = first;
  9. if (f == null)
  10. throw new NoSuchElementException();
  11. return f.item;
  12. }
  13. /**
  14. * Returns the last element in this list.
  15. *
  16. * @return the last element in this list
  17. * @throws NoSuchElementException if this list is empty
  18. */
  19. public E getLast() {
  20. final Node<E> l = last;
  21. if (l == null)
  22. throw new NoSuchElementException();
  23. return l.item;
  24. }

removeFirst(), removeLast(), remove(e), remove(index)

remove()方法也有两个版本,一个是删除跟指定元素相等的第一个元素remove(Object o),另一个是删除指定下标处的元素remove(int index)。
image.png

删除元素 - 指的是删除第一次出现的这个元素, 如果没有这个元素,则返回false;判断的依据是equals方法, 如果equals,则直接unlink这个node;由于LinkedList可存放null元素,故也可以删除第一次出现null的元素;

  1. /**
  2. * Removes the first occurrence of the specified element from this list,
  3. * if it is present. If this list does not contain the element, it is
  4. * unchanged. More formally, removes the element with the lowest index
  5. * {@code i} such that
  6. * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>
  7. * (if such an element exists). Returns {@code true} if this list
  8. * contained the specified element (or equivalently, if this list
  9. * changed as a result of the call).
  10. *
  11. * @param o element to be removed from this list, if present
  12. * @return {@code true} if this list contained the specified element
  13. */
  14. public boolean remove(Object o) {
  15. if (o == null) {
  16. for (Node<E> x = first; x != null; x = x.next) {
  17. if (x.item == null) {
  18. unlink(x);
  19. return true;
  20. }
  21. }
  22. } else {
  23. for (Node<E> x = first; x != null; x = x.next) {
  24. if (o.equals(x.item)) {
  25. unlink(x);
  26. return true;
  27. }
  28. }
  29. }
  30. return false;
  31. }
  32. /**
  33. * Unlinks non-null node x.
  34. */
  35. E unlink(Node<E> x) {
  36. // assert x != null;
  37. final E element = x.item;
  38. final Node<E> next = x.next;
  39. final Node<E> prev = x.prev;
  40. if (prev == null) {// 第一个元素
  41. first = next;
  42. } else {
  43. prev.next = next;
  44. x.prev = null;
  45. }
  46. if (next == null) {// 最后一个元素
  47. last = prev;
  48. } else {
  49. next.prev = prev;
  50. x.next = null;
  51. }
  52. x.item = null; // GC
  53. size--;
  54. modCount++;
  55. return element;
  56. }

remove(int index)使用的是下标计数, 只需要判断该index是否有元素即可,如果有则直接unlink这个node。

  1. /**
  2. * Removes the element at the specified position in this list. Shifts any
  3. * subsequent elements to the left (subtracts one from their indices).
  4. * Returns the element that was removed from the list.
  5. *
  6. * @param index the index of the element to be removed
  7. * @return the element previously at the specified position
  8. * @throws IndexOutOfBoundsException {@inheritDoc}
  9. */
  10. public E remove(int index) {
  11. checkElementIndex(index);
  12. return unlink(node(index));
  13. }

删除head元素:

  1. /**
  2. * Removes and returns the first element from this list.
  3. *
  4. * @return the first element from this list
  5. * @throws NoSuchElementException if this list is empty
  6. */
  7. public E removeFirst() {
  8. final Node<E> f = first;
  9. if (f == null)
  10. throw new NoSuchElementException();
  11. return unlinkFirst(f);
  12. }
  13. /**
  14. * Unlinks non-null first node f.
  15. */
  16. private E unlinkFirst(Node<E> f) {
  17. // assert f == first && f != null;
  18. final E element = f.item;
  19. final Node<E> next = f.next;
  20. f.item = null;
  21. f.next = null; // help GC
  22. first = next;
  23. if (next == null)
  24. last = null;
  25. else
  26. next.prev = null;
  27. size--;
  28. modCount++;
  29. return element;
  30. }

删除last元素:

  1. /**
  2. * Removes and returns the last element from this list.
  3. *
  4. * @return the last element from this list
  5. * @throws NoSuchElementException if this list is empty
  6. */
  7. public E removeLast() {
  8. final Node<E> l = last;
  9. if (l == null)
  10. throw new NoSuchElementException();
  11. return unlinkLast(l);
  12. }
  13. /**
  14. * Unlinks non-null last node l.
  15. */
  16. private E unlinkLast(Node<E> l) {
  17. // assert l == last && l != null;
  18. final E element = l.item;
  19. final Node<E> prev = l.prev;
  20. l.item = null;
  21. l.prev = null; // help GC
  22. last = prev;
  23. if (prev == null)
  24. first = null;
  25. else
  26. prev.next = null;
  27. size--;
  28. modCount++;
  29. return element;
  30. }

add()

add()方法有两个版本,一个是add(E e),该方法在LinkedList的末尾插入元素,因为有last指向链表末尾,在末尾插入元素的花费是常数时间。只需要简单修改几个相关引用即可;另一个是add(int index, E element),该方法是在指定下表处插入元素,需要先通过线性查找找到具体位置,然后修改相关引用完成插入操作。

  1. /**
  2. * Appends the specified element to the end of this list.
  3. *
  4. * <p>This method is equivalent to {@link #addLast}.
  5. *
  6. * @param e element to be appended to this list
  7. * @return {@code true} (as specified by {@link Collection#add})
  8. */
  9. public boolean add(E e) {
  10. linkLast(e);
  11. return true;
  12. }
  13. /**
  14. * Links e as last element.
  15. */
  16. void linkLast(E e) {
  17. final Node<E> l = last;
  18. final Node<E> newNode = new Node<>(l, e, null);
  19. last = newNode;
  20. if (l == null)
  21. first = newNode;
  22. else
  23. l.next = newNode;
  24. size++;
  25. modCount++;
  26. }

image.png

add(int index, E element), 当index==size时,等同于add(E e); 如果不是,则分两步: 1.先根据index找到要插入的位置,即node(index)方法;2.修改引用,完成插入操作。

  1. /**
  2. * Inserts the specified element at the specified position in this list.
  3. * Shifts the element currently at that position (if any) and any
  4. * subsequent elements to the right (adds one to their indices).
  5. *
  6. * @param index index at which the specified element is to be inserted
  7. * @param element element to be inserted
  8. * @throws IndexOutOfBoundsException {@inheritDoc}
  9. */
  10. public void add(int index, E element) {
  11. checkPositionIndex(index);
  12. if (index == size)
  13. linkLast(element);
  14. else
  15. linkBefore(element, node(index));
  16. }

上面代码中的node(int index)函数有一点小小的trick,因为链表双向的,可以从开始往后找,也可以从结尾往前找,具体朝那个方向找取决于条件index < (size >> 1),也即是index是靠近前端还是后端。从这里也可以看出,linkedList通过index检索元素的效率没有arrayList高。

  1. /**
  2. * Returns the (non-null) Node at the specified element index.
  3. */
  4. Node<E> node(int index) {
  5. // assert isElementIndex(index);
  6. if (index < (size >> 1)) {
  7. Node<E> x = first;
  8. for (int i = 0; i < index; i++)
  9. x = x.next;
  10. return x;
  11. } else {
  12. Node<E> x = last;
  13. for (int i = size - 1; i > index; i--)
  14. x = x.prev;
  15. return x;
  16. }
  17. }

addAll()

addAll(index, c) 实现方式并不是直接调用add(index,e)来实现,主要是因为效率的问题,另一个是fail-fast中modCount只会增加1次;

  1. /**
  2. * Appends all of the elements in the specified collection to the end of
  3. * this list, in the order that they are returned by the specified
  4. * collection's iterator. The behavior of this operation is undefined if
  5. * the specified collection is modified while the operation is in
  6. * progress. (Note that this will occur if the specified collection is
  7. * this list, and it's nonempty.)
  8. *
  9. * @param c collection containing elements to be added to this list
  10. * @return {@code true} if this list changed as a result of the call
  11. * @throws NullPointerException if the specified collection is null
  12. */
  13. public boolean addAll(Collection<? extends E> c) {
  14. return addAll(size, c);
  15. }
  16. /**
  17. * Inserts all of the elements in the specified collection into this
  18. * list, starting at the specified position. Shifts the element
  19. * currently at that position (if any) and any subsequent elements to
  20. * the right (increases their indices). The new elements will appear
  21. * in the list in the order that they are returned by the
  22. * specified collection's iterator.
  23. *
  24. * @param index index at which to insert the first element
  25. * from the specified collection
  26. * @param c collection containing elements to be added to this list
  27. * @return {@code true} if this list changed as a result of the call
  28. * @throws IndexOutOfBoundsException {@inheritDoc}
  29. * @throws NullPointerException if the specified collection is null
  30. */
  31. public boolean addAll(int index, Collection<? extends E> c) {
  32. checkPositionIndex(index);
  33. Object[] a = c.toArray();
  34. int numNew = a.length;
  35. if (numNew == 0)
  36. return false;
  37. Node<E> pred, succ;
  38. if (index == size) {
  39. succ = null;
  40. pred = last;
  41. } else {
  42. succ = node(index);
  43. pred = succ.prev;
  44. }
  45. for (Object o : a) {
  46. @SuppressWarnings("unchecked") E e = (E) o;
  47. Node<E> newNode = new Node<>(pred, e, null);
  48. if (pred == null)
  49. first = newNode;
  50. else
  51. pred.next = newNode;
  52. pred = newNode;
  53. }
  54. if (succ == null) {
  55. last = pred;
  56. } else {
  57. pred.next = succ;
  58. succ.prev = pred;
  59. }
  60. size += numNew;
  61. modCount++;
  62. return true;
  63. }

clear()

为了让GC更快可以回收放置的元素,需要将node之间的引用关系赋空。

  1. /**
  2. * Removes all of the elements from this list.
  3. * The list will be empty after this call returns.
  4. */
  5. public void clear() {
  6. // Clearing all of the links between nodes is "unnecessary", but:
  7. // - helps a generational GC if the discarded nodes inhabit
  8. // more than one generation
  9. // - is sure to free memory even if there is a reachable Iterator
  10. for (Node<E> x = first; x != null; ) {
  11. Node<E> next = x.next;
  12. x.item = null;
  13. x.next = null;
  14. x.prev = null;
  15. x = next;
  16. }
  17. first = last = null;
  18. size = 0;
  19. modCount++;
  20. }

Positional Access 方法

通过index获取元素

  1. /**
  2. * Returns the element at the specified position in this list.
  3. *
  4. * @param index index of the element to return
  5. * @return the element at the specified position in this list
  6. * @throws IndexOutOfBoundsException {@inheritDoc}
  7. */
  8. public E get(int index) {
  9. checkElementIndex(index);
  10. return node(index).item;
  11. }

将某个位置的元素重新赋值:

  1. /**
  2. * Replaces the element at the specified position in this list with the
  3. * specified element.
  4. *
  5. * @param index index of the element to replace
  6. * @param element element to be stored at the specified position
  7. * @return the element previously at the specified position
  8. * @throws IndexOutOfBoundsException {@inheritDoc}
  9. */
  10. public E set(int index, E element) {
  11. checkElementIndex(index);
  12. Node<E> x = node(index);
  13. E oldVal = x.item;
  14. x.item = element;
  15. return oldVal;
  16. }

将元素插入到指定index位置:

  1. /**
  2. * Inserts the specified element at the specified position in this list.
  3. * Shifts the element currently at that position (if any) and any
  4. * subsequent elements to the right (adds one to their indices).
  5. *
  6. * @param index index at which the specified element is to be inserted
  7. * @param element element to be inserted
  8. * @throws IndexOutOfBoundsException {@inheritDoc}
  9. */
  10. public void add(int index, E element) {
  11. checkPositionIndex(index);
  12. if (index == size)
  13. linkLast(element);
  14. else
  15. linkBefore(element, node(index));
  16. }

删除指定位置的元素:

  1. /**
  2. * Removes the element at the specified position in this list. Shifts any
  3. * subsequent elements to the left (subtracts one from their indices).
  4. * Returns the element that was removed from the list.
  5. *
  6. * @param index the index of the element to be removed
  7. * @return the element previously at the specified position
  8. * @throws IndexOutOfBoundsException {@inheritDoc}
  9. */
  10. public E remove(int index) {
  11. checkElementIndex(index);
  12. return unlink(node(index));
  13. }

其它位置的方法:

  1. /**
  2. * Tells if the argument is the index of an existing element.
  3. */
  4. private boolean isElementIndex(int index) {
  5. return index >= 0 && index < size;
  6. }
  7. /**
  8. * Tells if the argument is the index of a valid position for an
  9. * iterator or an add operation.
  10. */
  11. private boolean isPositionIndex(int index) {
  12. return index >= 0 && index <= size;
  13. }
  14. /**
  15. * Constructs an IndexOutOfBoundsException detail message.
  16. * Of the many possible refactorings of the error handling code,
  17. * this "outlining" performs best with both server and client VMs.
  18. */
  19. private String outOfBoundsMsg(int index) {
  20. return "Index: "+index+", Size: "+size;
  21. }
  22. private void checkElementIndex(int index) {
  23. if (!isElementIndex(index))
  24. throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  25. }
  26. private void checkPositionIndex(int index) {
  27. if (!isPositionIndex(index))
  28. throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  29. }

查找操作

查找操作的本质是查找元素的下标:
查找第一次出现的index, 如果找不到返回-1;

  1. /**
  2. * Returns the index of the first occurrence of the specified element
  3. * in this list, or -1 if this list does not contain the element.
  4. * More formally, returns the lowest index {@code i} such that
  5. * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
  6. * or -1 if there is no such index.
  7. *
  8. * @param o element to search for
  9. * @return the index of the first occurrence of the specified element in
  10. * this list, or -1 if this list does not contain the element
  11. */
  12. public int indexOf(Object o) {
  13. int index = 0;
  14. if (o == null) {
  15. for (Node<E> x = first; x != null; x = x.next) {
  16. if (x.item == null)
  17. return index;
  18. index++;
  19. }
  20. } else {
  21. for (Node<E> x = first; x != null; x = x.next) {
  22. if (o.equals(x.item))
  23. return index;
  24. index++;
  25. }
  26. }
  27. return -1;
  28. }

查找最后一次出现的index, 如果找不到返回-1;

  1. /**
  2. * Returns the index of the last occurrence of the specified element
  3. * in this list, or -1 if this list does not contain the element.
  4. * More formally, returns the highest index {@code i} such that
  5. * <tt>(o==null&nbsp;?&nbsp;get(i)==null&nbsp;:&nbsp;o.equals(get(i)))</tt>,
  6. * or -1 if there is no such index.
  7. *
  8. * @param o element to search for
  9. * @return the index of the last occurrence of the specified element in
  10. * this list, or -1 if this list does not contain the element
  11. */
  12. public int lastIndexOf(Object o) {
  13. int index = size;
  14. if (o == null) {
  15. for (Node<E> x = last; x != null; x = x.prev) {
  16. index--;
  17. if (x.item == null)
  18. return index;
  19. }
  20. } else {
  21. for (Node<E> x = last; x != null; x = x.prev) {
  22. index--;
  23. if (o.equals(x.item))
  24. return index;
  25. }
  26. }
  27. return -1;
  28. }

Queue 方法

  1. /**
  2. * Retrieves, but does not remove, the head (first element) of this list.
  3. *
  4. * @return the head of this list, or {@code null} if this list is empty
  5. * @since 1.5
  6. */
  7. public E peek() {
  8. final Node<E> f = first;
  9. return (f == null) ? null : f.item;
  10. }
  11. /**
  12. * Retrieves, but does not remove, the head (first element) of this list.
  13. *
  14. * @return the head of this list
  15. * @throws NoSuchElementException if this list is empty
  16. * @since 1.5
  17. */
  18. public E element() {
  19. return getFirst();
  20. }
  21. /**
  22. * Retrieves and removes the head (first element) of this list.
  23. *
  24. * @return the head of this list, or {@code null} if this list is empty
  25. * @since 1.5
  26. */
  27. public E poll() {
  28. final Node<E> f = first;
  29. return (f == null) ? null : unlinkFirst(f);
  30. }
  31. /**
  32. * Retrieves and removes the head (first element) of this list.
  33. *
  34. * @return the head of this list
  35. * @throws NoSuchElementException if this list is empty
  36. * @since 1.5
  37. */
  38. public E remove() {
  39. return removeFirst();
  40. }
  41. /**
  42. * Adds the specified element as the tail (last element) of this list.
  43. *
  44. * @param e the element to add
  45. * @return {@code true} (as specified by {@link Queue#offer})
  46. * @since 1.5
  47. */
  48. public boolean offer(E e) {
  49. return add(e);
  50. }

Deque 方法

  1. /**
  2. * Inserts the specified element at the front of this list.
  3. *
  4. * @param e the element to insert
  5. * @return {@code true} (as specified by {@link Deque#offerFirst})
  6. * @since 1.6
  7. */
  8. public boolean offerFirst(E e) {
  9. addFirst(e);
  10. return true;
  11. }
  12. /**
  13. * Inserts the specified element at the end of this list.
  14. *
  15. * @param e the element to insert
  16. * @return {@code true} (as specified by {@link Deque#offerLast})
  17. * @since 1.6
  18. */
  19. public boolean offerLast(E e) {
  20. addLast(e);
  21. return true;
  22. }
  23. /**
  24. * Retrieves, but does not remove, the first element of this list,
  25. * or returns {@code null} if this list is empty.
  26. *
  27. * @return the first element of this list, or {@code null}
  28. * if this list is empty
  29. * @since 1.6
  30. */
  31. public E peekFirst() {
  32. final Node<E> f = first;
  33. return (f == null) ? null : f.item;
  34. }
  35. /**
  36. * Retrieves, but does not remove, the last element of this list,
  37. * or returns {@code null} if this list is empty.
  38. *
  39. * @return the last element of this list, or {@code null}
  40. * if this list is empty
  41. * @since 1.6
  42. */
  43. public E peekLast() {
  44. final Node<E> l = last;
  45. return (l == null) ? null : l.item;
  46. }
  47. /**
  48. * Retrieves and removes the first element of this list,
  49. * or returns {@code null} if this list is empty.
  50. *
  51. * @return the first element of this list, or {@code null} if
  52. * this list is empty
  53. * @since 1.6
  54. */
  55. public E pollFirst() {
  56. final Node<E> f = first;
  57. return (f == null) ? null : unlinkFirst(f);
  58. }
  59. /**
  60. * Retrieves and removes the last element of this list,
  61. * or returns {@code null} if this list is empty.
  62. *
  63. * @return the last element of this list, or {@code null} if
  64. * this list is empty
  65. * @since 1.6
  66. */
  67. public E pollLast() {
  68. final Node<E> l = last;
  69. return (l == null) ? null : unlinkLast(l);
  70. }
  71. /**
  72. * Pushes an element onto the stack represented by this list. In other
  73. * words, inserts the element at the front of this list.
  74. *
  75. * <p>This method is equivalent to {@link #addFirst}.
  76. *
  77. * @param e the element to push
  78. * @since 1.6
  79. */
  80. public void push(E e) {
  81. addFirst(e);
  82. }
  83. /**
  84. * Pops an element from the stack represented by this list. In other
  85. * words, removes and returns the first element of this list.
  86. *
  87. * <p>This method is equivalent to {@link #removeFirst()}.
  88. *
  89. * @return the element at the front of this list (which is the top
  90. * of the stack represented by this list)
  91. * @throws NoSuchElementException if this list is empty
  92. * @since 1.6
  93. */
  94. public E pop() {
  95. return removeFirst();
  96. }
  97. /**
  98. * Removes the first occurrence of the specified element in this
  99. * list (when traversing the list from head to tail). If the list
  100. * does not contain the element, it is unchanged.
  101. *
  102. * @param o element to be removed from this list, if present
  103. * @return {@code true} if the list contained the specified element
  104. * @since 1.6
  105. */
  106. public boolean removeFirstOccurrence(Object o) {
  107. return remove(o);
  108. }
  109. /**
  110. * Removes the last occurrence of the specified element in this
  111. * list (when traversing the list from head to tail). If the list
  112. * does not contain the element, it is unchanged.
  113. *
  114. * @param o element to be removed from this list, if present
  115. * @return {@code true} if the list contained the specified element
  116. * @since 1.6
  117. */
  118. public boolean removeLastOccurrence(Object o) {
  119. if (o == null) {
  120. for (Node<E> x = last; x != null; x = x.prev) {
  121. if (x.item == null) {
  122. unlink(x);
  123. return true;
  124. }
  125. }
  126. } else {
  127. for (Node<E> x = last; x != null; x = x.prev) {
  128. if (o.equals(x.item)) {
  129. unlink(x);
  130. return true;
  131. }
  132. }
  133. }
  134. return false;
  135. }

参考