资讯专栏INFORMATION COLUMN

LinkedList源码解析

番茄西红柿 / 1324人阅读

摘要:我们来看相关源码我们看到封装的和操作其实就是对头结点的操作。迭代器通过指针,能指向下一个节点,无需做额外的遍历,速度非常快。不同的遍历性能差距极大,推荐使用迭代器进行遍历。

LinkedList类介绍

上一篇文章我们介绍了JDK中ArrayList的实现,ArrayList底层结构是一个Object[]数组,通过拷贝,复制等一系列封装的操作,将数组封装为一个几乎是无限的容器。今天我们来介绍JDK中List接口的另外一种实现,基于链表结构的LinkedList。ArrayList由于基于数组,所以在随机访问方面优势比较明显,在删除、插入方面性能会相对偏弱些(当然与删除、插入的位置有很大关系)。那么LinkedList有哪些优势呢?它在删除、插入方面的操作很简单(只是调整相关指针而已)。但是随机访问方面要逊色写。下面我们还是从源码上来看下这种链表结构的List。

LinkedList类主要字段

</>复制代码

  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 first;
  8. /**
  9. * Pointer to last node.
  10. * Invariant: (first == null && last == null) ||
  11. * (last.next == null && last.item != null)
  12. */
  13. transient Node last;

我们看到字段非常少,size表示当前节点数量,first指向链表的起始元素、last指向链表的最后一个元素。

Node结构

从上面主要字段看出,LinkedList链表的Item就是一个Node结构,那么Node结构是怎样的呢?源码如下:

</>复制代码

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

我们看到Node结构包含一个前驱prev指针,item(value)、后继next指针三个部分。结合上面的描述,我们知道了LinkedList的主要结构。如图:

第一个节点的prev指向NULL,最后一个节点的next指向NULL。其余节点通过prev与next串联起来,LinkedList提供了从任意节点都能进行向前或先后遍历的能力。

LinkedList相关方法解析 构造函数

</>复制代码

  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 collections
  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<);

由于LinkedList是通过prev与next指针链接起来的,有元素添加时只需要一个个设置指针将其链接起来即可,所以构造函数相对较简洁。我们重点来看下第二个构造函数中的addAll方法。

addAll方法

</>复制代码

  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. * collections 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 its 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<);return addAll(size, c);
  14. }
  15. /**
  16. * Inserts all of the elements in the specified collection into this
  17. * list, starting at the specified position. Shifts the element
  18. * currently at that position (if any) and any subsequent elements to
  19. * the right (increases their indices). The new elements will appear
  20. * in the list in the order that they are returned by the
  21. * specified collections iterator.
  22. *
  23. * @param index index at which to insert the first element
  24. * from the specified collection
  25. * @param c collection containing elements to be added to this list
  26. * @return {@code true} if this list changed as a result of the call
  27. * @throws IndexOutOfBoundsException {@inheritDoc}
  28. * @throws NullPointerException if the specified collection is null
  29. */
  30. public boolean addAll(int index, Collection<);if (numNew == 0)
  31. return false;
  32. Node pred, succ;
  33. if (index == size) {
  34. succ = null;
  35. pred = last;
  36. } else {
  37. succ = node(index);
  38. pred = succ.prev;
  39. }
  40. for (Object o : a) {
  41. @SuppressWarnings("unchecked") E e = (E) o;
  42. Node newNode = new Node<>(pred, e, null);
  43. if (pred == null)
  44. first = newNode;
  45. else
  46. pred.next = newNode;
  47. pred = newNode;
  48. }
  49. if (succ == null) {
  50. last = pred;
  51. } else {
  52. pred.next = succ;
  53. succ.prev = pred;
  54. }
  55. size += numNew;
  56. modCount++;
  57. return true;
  58. }
  59. /**
  60. * Returns the (non-null) Node at the specified element index.
  61. */
  62. Node node(int index) {
  63. // assert isElementIndex(index);
  64. if (index < (size >> 1)) {
  65. Node x = first;
  66. for (int i = 0; i < index; i++)
  67. x = x.next;
  68. return x;
  69. } else {
  70. Node x = last;
  71. for (int i = size - 1; i > index; i--)
  72. x = x.prev;
  73. return x;
  74. }
  75. }

addAll方法是将Collection集合插入链表。下面我们来仔细分析整个过程(涉及比较多的指针操作)。

首先代码检查index的值的正确性,如果index位置不合理会直接抛出异常。

然后将待插入集合转化成数组,判断集合长度。

根据index值,分别设置pred和succ指针。如果插入的位置是当前链表尾部,那么pred指向最后一个元素,succ暂时设置为NULL即可。如果插入位置在链表中间,那么先通过node方法找到当前链表的index位置的元素,succ指向它。pred指向待插入位置的前一个节点,succ指向当前index位置的节点,新插入的节点就是在pred和succ节点之间。

for循环创建Node节点,先将pred.next指向新创建的节点,然后pred指向后移,指向新创建的Node节点,重复上述过程,这样一个个节点就被创建,链接起来了。

最后根据情况不同,将succ指向的那个节点作为最后的节点,当然如果succ为NULL的话,last指针指向pred。

removeFirst()方法和removeLast()方法

removeFirst方法会返回当前链表的头部节点值,然后将头结点指向下一个节点,我们通过源码来分析:

</>复制代码

  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 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 f) {
  17. // assert f == first && f != null;
  18. final E element = f.item;
  19. final Node 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. }

我们看到主要逻辑在unlinkFirst方法中,逻辑还是比较清晰的,first指针指向next节点,该节点作为新的链表头部,只是最后需要处理下边界值(next==null)的情况。removeLast方法类似,大家可以去分析源码。

addFirst方法和addLast()方法

addFirst方法是将新节点插入链表,并且将新节点作为链表头部,下面我们来看源码:

</>复制代码

  1. /**
  2. * Inserts the specified element at the beginning of this list.
  3. *
  4. * @param e the element to add
  5. */
  6. public void addFirst(E e) {
  7. linkFirst(e);
  8. }
  9. /**
  10. * Links e as first element.
  11. */
  12. private void linkFirst(E e) {
  13. final Node f = first;
  14. final Node newNode = new Node<>(null, e, f);
  15. first = newNode;
  16. if (f == null)
  17. last = newNode;
  18. else
  19. f.prev = newNode;
  20. size++;
  21. modCount++;
  22. }

代码逻辑比较清晰,newNode节点在创建时,由于是作为新的头结点的,所以prev必须是NULL的,next是指向当前头结点f。接下来就是设置first,处理边界值了。
下面我们来看下addLast方法,源码如下:

</>复制代码

  1. /**
  2. * Appends the specified element to the end of this list.
  3. *
  4. *

    This method is equivalent to {@link #add}.

  5. *
  6. * @param e the element to add
  7. */
  8. public void addLast(E e) {
  9. linkLast(e);
  10. }
  11. /**
  12. * Links e as last element.
  13. */
  14. void linkLast(E e) {
  15. final Node l = last;
  16. final Node newNode = new Node<>(l, e, null);
  17. last = newNode;
  18. if (l == null)
  19. first = newNode;
  20. else
  21. l.next = newNode;
  22. size++;
  23. modCount++;
  24. }
add方法和remove方法

这两个方法是我们使用频率很高的方法,我们来看下其内部实现:

</>复制代码

  1. /**
  2. * Appends the specified element to the end of this list.
  3. *
  4. *

    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. * Removes the first occurrence of the specified element from this list,
  15. * if it is present. If this list does not contain the element, it is
  16. * unchanged. More formally, removes the element with the lowest index
  17. * {@code i} such that
  18. * (o==null );if such an element exists). Returns {@code true} if this list
  19. * contained the specified element (or equivalently, if this list
  20. * changed as a result of the call).
  21. *
  22. * @param o element to be removed from this list, if present
  23. * @return {@code true} if this list contained the specified element
  24. */
  25. public boolean remove(Object o) {
  26. if (o == null) {
  27. for (Node x = first; x != null; x = x.next) {
  28. if (x.item == null) {
  29. unlink(x);
  30. return true;
  31. }
  32. }
  33. } else {
  34. for (Node x = first; x != null; x = x.next) {
  35. if (o.equals(x.item)) {
  36. unlink(x);
  37. return true;
  38. }
  39. }
  40. }
  41. return false;
  42. }
  43. /**
  44. * Unlinks non-null node x.
  45. */
  46. E unlink(Node x) {
  47. // assert x != null;
  48. final E element = x.item;
  49. final Node next = x.next;
  50. final Node prev = x.prev;
  51. if (prev == null) {
  52. first = next;
  53. } else {
  54. prev.next = next;
  55. x.prev = null;
  56. }
  57. if (next == null) {
  58. last = prev;
  59. } else {
  60. next.prev = prev;
  61. x.next = null;
  62. }
  63. x.item = null;
  64. size--;
  65. modCount++;
  66. return element;
  67. }

我们看到add方法其实就是对linkLast方法的封装(当然,这是末尾添加)。remove方法逻辑会复杂些,需要先找到指定节点,然后调用unlink方法。
unlink方法解析
我们看到unlink方法首先将需要删除的节点的prev和next保存起来,因为后面需要将两者连接起来。然后将prev和next分别判断设置(包括边界值的考虑),最后将x节点的数据设置为NULL。

clear方法

LinkedList链表结构的,它的clear方法是如何实现的呢?我们来看下:

</>复制代码

  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 x = first; x != null; ) {
  11. Node 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. }

代码还是比较清晰的,就是从头结点开始,将Node节点一个个的设置为NULL,方便GC回收。

LinkedList与队列操作

有数据结构基础的同学应该都知道队列的结构,这是一种先进先出的结构。从JDK1.5开始,LinkedList内部集成了队列的操作,LinkedList可以当做一个基本的队列进行使用。下面我们从队列的角度来看下LinkedList提供的相关方法。

peek、poll、element、remove方法

</>复制代码

  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 f = first;
  9. return (f == null) );return the head of this list
  10. * @throws NoSuchElementException if this list is empty
  11. * @since 1.5
  12. */
  13. public E element() {
  14. return getFirst();
  15. }
  16. /**
  17. * Retrieves and removes the head (first element) of this list.
  18. *
  19. * @return the head of this list, or {@code null} if this list is empty
  20. * @since 1.5
  21. */
  22. public E poll() {
  23. final Node f = first;
  24. return (f == null) );return the head of this list
  25. * @throws NoSuchElementException if this list is empty
  26. * @since 1.5
  27. */
  28. public E remove() {
  29. return removeFirst();
  30. }

从上面的方法,我们知道peek、element方法只返回队列头部数据,不移除头部。而poll、remove方法返回队列头部数据的同是,还会移除头部。

offer方法

</>复制代码

  1. /**
  2. * Adds the specified element as the tail (last element) of this list.
  3. *
  4. * @param e the element to add
  5. * @return {@code true} (as specified by {@link Queue#offer})
  6. * @since 1.5
  7. */
  8. public boolean offer(E e) {
  9. return add(e);
  10. }

从上面的代码中我们看到,offer方法其实就是入队操作。

LinkedList与双端队列

上面我们介绍了使用LinkedList来作为队列的相关方法,在JDK6中添加相关方法让LinkedList支持双端队列。源代码如下:

</>复制代码

  1. // Deque operations
  2. /**
  3. * Inserts the specified element at the front of this list.
  4. *
  5. * @param e the element to insert
  6. * @return {@code true} (as specified by {@link Deque#offerFirst})
  7. * @since 1.6
  8. */
  9. public boolean offerFirst(E e) {
  10. addFirst(e);
  11. return true;
  12. }
  13. /**
  14. * Inserts the specified element at the end of this list.
  15. *
  16. * @param e the element to insert
  17. * @return {@code true} (as specified by {@link Deque#offerLast})
  18. * @since 1.6
  19. */
  20. public boolean offerLast(E e) {
  21. addLast(e);
  22. return true;
  23. }
  24. /**
  25. * Retrieves, but does not remove, the first element of this list,
  26. * or returns {@code null} if this list is empty.
  27. *
  28. * @return the first element of this list, or {@code null}
  29. * if this list is empty
  30. * @since 1.6
  31. */
  32. public E peekFirst() {
  33. final Node f = first;
  34. return (f == null) );if this list is empty.
  35. *
  36. * @return the last element of this list, or {@code null}
  37. * if this list is empty
  38. * @since 1.6
  39. */
  40. public E peekLast() {
  41. final Node l = last;
  42. return (l == null) );if this list is empty.
  43. *
  44. * @return the first element of this list, or {@code null} if
  45. * this list is empty
  46. * @since 1.6
  47. */
  48. public E pollFirst() {
  49. final Node f = first;
  50. return (f == null) );if this list is empty.
  51. *
  52. * @return the last element of this list, or {@code null} if
  53. * this list is empty
  54. * @since 1.6
  55. */
  56. public E pollLast() {
  57. final Node l = last;
  58. return (l == null) );

上面的代码逻辑比较清楚,就不详细介绍了。

LinkedList与栈(Stack)

堆栈大伙肯定很熟悉,是一种先进后出的结构。类似于叠盘子,一般我们使用的时候肯定从最上面拿取。栈也是这样,最后进入的,最先出去。LinkedList在JDK6的时候也添加了对栈的支持。我们来看相关源码:

</>复制代码

  1. /**
  2. * Pushes an element onto the stack represented by this list. In other
  3. * words, inserts the element at the front of this list.
  4. *
  5. *

    This method is equivalent to {@link #addFirst}.

  6. *
  7. * @param e the element to push
  8. * @since 1.6
  9. */
  10. public void push(E e) {
  11. addFirst(e);
  12. }
  13. /**
  14. * Pops an element from the stack represented by this list. In other
  15. * words, removes and returns the first element of this list.
  16. *
  17. *

    This method is equivalent to {@link #removeFirst()}.

  18. *
  19. * @return the element at the front of this list (which is the top
  20. * of the stack represented by this list)
  21. * @throws NoSuchElementException if this list is empty
  22. * @since 1.6
  23. */
  24. public E pop() {
  25. return removeFirst();
  26. }

我们看到LinkedList封装的push和pop操作其实就是对first头结点的操作。通过对头结点不短了的push、pop来模拟堆栈先进后出的结构。

LinkedList与迭代器

</>复制代码

  1. private class ListItr implements ListIterator {
  2. private Node lastReturned;
  3. private Node next;
  4. private int nextIndex;
  5. private int expectedModCount = modCount;
  6. ListItr(int index) {
  7. // assert isPositionIndex(index);
  8. next = (index == size) );hasNext() {
  9. return nextIndex < size;
  10. }
  11. public E next() {
  12. checkForComodification();
  13. if (!hasNext())
  14. throw new NoSuchElementException();
  15. lastReturned = next;
  16. next = next.next;
  17. nextIndex++;
  18. return lastReturned.item;
  19. }
  20. public boolean hasPrevious() {
  21. return nextIndex > 0;
  22. }
  23. public E previous() {
  24. checkForComodification();
  25. if (!hasPrevious())
  26. throw new NoSuchElementException();
  27. lastReturned = next = (next == null) );return lastReturned.item;
  28. }
  29. public int nextIndex() {
  30. return nextIndex;
  31. }
  32. public int previousIndex() {
  33. return nextIndex - 1;
  34. }
  35. public void remove() {
  36. checkForComodification();
  37. if (lastReturned == null)
  38. throw new IllegalStateException();
  39. Node lastNext = lastReturned.next;
  40. unlink(lastReturned);
  41. if (next == lastReturned)
  42. next = lastNext;
  43. else
  44. nextIndex--;
  45. lastReturned = null;
  46. expectedModCount++;
  47. }
  48. public void set(E e) {
  49. if (lastReturned == null)
  50. throw new IllegalStateException();
  51. checkForComodification();
  52. lastReturned.item = e;
  53. }
  54. public void add(E e) {
  55. checkForComodification();
  56. lastReturned = null;
  57. if (next == null)
  58. linkLast(e);
  59. else
  60. linkBefore(e, next);
  61. nextIndex++;
  62. expectedModCount++;
  63. }
  64. public void forEachRemaining(Consumer<);while (modCount == expectedModCount && nextIndex < size) {
  65. action.accept(next.item);
  66. lastReturned = next;
  67. next = next.next;
  68. nextIndex++;
  69. }
  70. checkForComodification();
  71. }
  72. final void checkForComodification() {
  73. if (modCount != expectedModCount)
  74. throw new ConcurrentModificationException();
  75. }
  76. }

从上面的迭代器的源码我们可以知道以下几点:

1、LinkedList通过自定义迭代器实现了往前往后两个方向的遍历。

2、remove方法中next == lastReturned条件的判断是针对上一次对链表进行了previous操作后进行的判断。因为上一次previous操作后next指针会“悬空”。需要将其设置为next节点。

LinkedList遍历相关问题

对于集合来说,遍历是非常常规的操作。但是对于LinkedList来说,遍历的时候需要选择合适的方法,因为不合理的方法对于性能有非常大的差别。我们通过例子来看:

</>复制代码

  1. List list=new LinkedList<>();
  2. for(int i=0;i<10000;i++) {
  3. list.add(String.valueOf(i));
  4. }
  5. //遍历方法一
  6. long time=System.currentTimeMillis();
  7. for(int i=0;i iterator=list.iterator();
  8. while (iterator.hasNext()) {
  9. iterator.next();
  10. }
  11. iterator.remove();
  12. System.out.println(System.currentTimeMillis()-time);

输出如下:

</>复制代码

  1. size:10000的情况
  2. 120
  3. 2
  4. size:100000的情况
  5. 28949
  6. 2

同样是遍历方法,为什么性能差别几十倍,设置上万倍呢?研究过源码的同学应该能发现其中的奥秘。我们来看get方法的逻辑:

</>复制代码

  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. }
  12. /**
  13. * Returns the (non-null) Node at the specified element index.
  14. */
  15. Node node(int index) {
  16. // assert isElementIndex(index);
  17. if (index < (size >> 1)) {
  18. Node x = first;
  19. for (int i = 0; i < index; i++)
  20. x = x.next;
  21. return x;
  22. } else {
  23. Node x = last;
  24. for (int i = size - 1; i > index; i--)
  25. x = x.prev;
  26. return x;
  27. }
  28. }

我们看到,我们get(index)的时候,都需要从头,或者从尾部慢慢循环过来。get(4000)的时候需要从0-4000进行遍历。get(4001)的时候还是需要从0-4001进行遍历。做了无数的无用功。但是迭代器就不一样了。迭代器通过next指针,能指向下一个节点,无需做额外的遍历,速度非常快。

总结

1、LinkedList在添加及修改时候效率较高,只需要设置前后节点即可(ArrayList还需要拷贝前后数据)。

2、LinkedList不同的遍历性能差距极大,推荐使用迭代器进行遍历。LinkedList在随机访问方面性能一般(ArrayList随机方法可以使用基地址+偏移量的方式访问)

LinkedList提供作为队列、堆栈的相关方法。

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/7122.html

相关文章

  • LinkedList源码解析

    摘要:我们来看相关源码我们看到封装的和操作其实就是对头结点的操作。迭代器通过指针,能指向下一个节点,无需做额外的遍历,速度非常快。不同的遍历性能差距极大,推荐使用迭代器进行遍历。LinkedList类介绍 上一篇文章我们介绍了JDK中ArrayList的实现,ArrayList底层结构是一个Object[]数组,通过拷贝,复制等一系列封装的操作,将数组封装为一个几乎是无限的容器。今天我们来介绍JD...

    roundstones 评论0 收藏0
  • Java集合之LinkedList源码解析

    摘要:快速失败在用迭代器遍历一个集合对象时,如果遍历过程中对集合对象的内容进行了修改增加删除修改,则会抛出。原理由于迭代时是对原集合的拷贝进行遍历,所以在遍历过程中对原集合所作的修改并不能被迭代器检测到,所以不会触发。 原文地址 LinkedList 在Java.util包下 继承自AbstractSequentialList 实现 List 接口,能对它进行队列操作。 实现 Deque ...

    DC_er 评论0 收藏0
  • LinkedList 基本示例及源码解析

    摘要:对于不可修改的列表来说,程序员需要实现列表迭代器的和方法介绍这个接口也是继承类层次的核心接口,以求最大限度的减少实现此接口的工作量,由顺序访问数据存储例如链接链表支持。 一、JavaDoc 简介 LinkedList双向链表,实现了List的 双向队列接口,实现了所有list可选择性操作,允许存储任何元素(包括null值) 所有的操作都可以表现为双向性的,遍历的时候会从首部到尾部进行...

    senntyou 评论0 收藏0
  • LinkedList源码解析

    摘要:我们来看相关源码我们看到封装的和操作其实就是对头结点的操作。迭代器通过指针,能指向下一个节点,无需做额外的遍历,速度非常快。不同的遍历性能差距极大,推荐使用迭代器进行遍历。LinkedList类介绍 上一篇文章我们介绍了JDK中ArrayList的实现,ArrayList底层结构是一个Object[]数组,通过拷贝,复制等一系列封装的操作,将数组封装为一个几乎是无限的容器。今天我们来介绍JD...

    番茄西红柿 评论0 收藏0
  • LinkedList源码解析(一)

    摘要:基本属性存储数据量指向第一个节点的指针指向最后一个节点的指针。 基本属性 transient int size = 0;//存储数据量 /** * Pointer to first node. */ transient Node first;//指向第一个节点的指针 /** * Pointer to last node...

    GT 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<