LinkedList源码分析

超、凢脫俗 2022-03-26 04:54 530阅读 0赞

在我的印象里LinkedList的使用场景并没有ArrayList多,我一度认为ArrayList并没有LinkedList复杂,毕竟LinkedList是链表实现的。但是在我读完LinkedList的源码后发现,LinkedList的源码并没有ArrayList那么多的数组copy。只是单纯的链表操作。
首先看类定义

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

linkedList实现了AbstractSequentialList 这个类是一个抽象类,并且继承自AbstractList。我们知道ArrayList是直接继承自AbstractList的,这两者之间有何区别呢。
AbstractList实现随机访问数据存储集合的默认实现,例如数组 的实现ArrayList
AbstractSequentialList 实现顺序访问数据存储集合的默认实现 例如链表 的实现LinkedList
我们来对比一下两者的几个核心方法的实现
AbstractList

  1. public boolean add(E e) {
  2. add(size(), e);
  3. return true;
  4. }
  5. abstract public E get(int index);
  6. public E set(int index, E element) {
  7. throw new UnsupportedOperationException();
  8. }

AbstractSequentialList

  1. public void add(int index, E element) {
  2. try {
  3. listIterator(index).add(element);
  4. } catch (NoSuchElementException exc) {
  5. throw new IndexOutOfBoundsException("Index: "+index);
  6. }
  7. }
  8. public E get(int index) {
  9. try {
  10. return listIterator(index).next();
  11. } catch (NoSuchElementException exc) {
  12. throw new IndexOutOfBoundsException("Index: "+index);
  13. }
  14. }
  15. public E set(int index, E element) {
  16. try {
  17. ListIterator<E> e = listIterator(index);
  18. E oldVal = e.next();
  19. e.set(element);
  20. return oldVal;
  21. } catch (NoSuchElementException exc) {
  22. throw new IndexOutOfBoundsException("Index: "+index);
  23. }
  24. }

可以看到AbstractSequentialList 的实现使用的都是迭代器。迭代器只能顺序访问,这就很适合链表结构的数据结构。并且LinkedList还实现了Deque接口,Deque接口又实现了Queue接口,
Deque是一种双向队列的形式,支持在两端方向检索。
接下来开始正题:
要看LinkedList首先就要看他的数据结构 ,他核心的数据结构就是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>3>4>5>null
但是光有Node是不够的 一个链表需要首尾 这时继续往下看,LinkedList的属性

  1. public class LinkedList<E>
  2. extends AbstractSequentialList<E>
  3. implements List<E>, Deque<E>, Cloneable, java.io.Serializable
  4. {
  5. // 定义list长度
  6. transient int size = 0;
  7. /** * Pointer to first node. * Invariant: (first == null && last == null) || * (first.prev == null && first.item != null) */
  8. // 首
  9. transient Node<E> first;
  10. /** * Pointer to last node. * Invariant: (first == null && last == null) || * (last.next == null && last.item != null) */
  11. // 尾
  12. transient Node<E> last;

有了首尾,再加上 Node 的数据结构 一个链表就能够构建了。接下来我们看一下他的方法。为了方便理解,这里Node 可以理解为 一个指针
首先来看linkFirst方法

  1. //赋值链表的第一个Node
  2. private void linkFirst(E e) {
  3. final Node<E> f = first; //得到当前的头指针
  4. final Node<E> newNode = new Node<>(null, e, f); //新的first 前没有node 后为原先的头指针
  5. first = newNode; // first变成新的头指针
  6. if (f == null) //如果 原来的first 是空 那么last就是这个链表里唯一的值,所以last也为他
  7. last = newNode;
  8. else
  9. f.prev = newNode; // 将原来的的头指针的前引用 变成了 现在的头指针
  10. size++;
  11. modCount++;
  12. }

同样有linkFirst 就有 linkLast

  1. void linkLast(E e) {
  2. final Node<E> l = last;
  3. final Node<E> newNode = new Node<>(l, e, null);
  4. last = newNode;
  5. if (l == null)
  6. first = newNode;
  7. else
  8. l.next = newNode; //将原来尾指针的后引用变成 新的尾指针
  9. size++;
  10. modCount++;
  11. }

之后我们来看一下 list中 最常用的方法

  1. public boolean add(E e) {
  2. linkLast(e); //这里调用了linkLast 向最后一位link一个值
  3. return true;
  4. }
  5. //核心思路就是讲原来的last的next变成e 将e的prev变成原先的last
  6. void linkLast(E e) {
  7. final Node<E> l = last;
  8. final Node<E> newNode = new Node<>(l, e, null);
  9. last = newNode;
  10. if (l == null)
  11. first = newNode;
  12. else
  13. l.next = newNode;
  14. size++;
  15. modCount++;
  16. }

是不是很好理解呢, 就是在原本的last后面再跟一个 并把这个新的作为last就好了。
接着再来看remove方法 remove 方法有两个,先说第一个

  1. //这里jdk做了 o==null的情况 如果==null 返回匹配到的第一个null值 ,否则去调用equals,这就是我们为何要去重写equals方法了。
  2. public boolean remove(Object o) {
  3. if (o == null) {
  4. for (Node<E> x = first; x != null; x = x.next) {
  5. if (x.item == null) {
  6. unlink(x);
  7. return true;
  8. }
  9. }
  10. } else {
  11. for (Node<E> x = first; x != null; x = x.next) {
  12. if (o.equals(x.item)) {
  13. unlink(x);
  14. return true;
  15. }
  16. }
  17. }
  18. return false;
  19. }
  20. //这里涉及到一个unlink方法
  21. E unlink(Node<E> x) {
  22. // assert x != null;
  23. final E element = x.item;
  24. final Node<E> next = x.next;
  25. final Node<E> prev = x.prev;
  26. //解绑 x的前后指针
  27. //并且他们原先指向 x的指针 变成了新的位置
  28. if (prev == null) {
  29. first = next;
  30. } else {
  31. prev.next = next;
  32. x.prev = null;
  33. }
  34. if (next == null) {
  35. last = prev;
  36. } else {
  37. next.prev = prev;
  38. x.next = null;
  39. }
  40. //把x的值置为空
  41. x.item = null;
  42. size--;
  43. modCount++;
  44. return element;
  45. }

接下来我们看一下addAll这个方法

  1. public boolean addAll(int index, Collection<? extends E> c) {
  2. //校验index是否在范围内 这里的范围指的是 index不能小于0 且 index不能大于size(大于size 比如index = size +1 你size位置上的尾指针应该是谁的头指针呢?)
  3. checkPositionIndex(index);
  4. // 转成Obj数组
  5. Object[] a = c.toArray();
  6. int numNew = a.length;
  7. if (numNew == 0)
  8. return false;
  9. //这里只需要 前一个节点 和当前节点就够了
  10. Node<E> pred, succ;
  11. if (index == size) {
  12. //如果要往最后一个节点之后插入node 当前就是null 上一个节点就是原来的last
  13. succ = null;
  14. pred = last;
  15. } else {
  16. // 否则获取当前index位置的节点
  17. succ = node(index);
  18. pred = succ.prev;
  19. }
  20. for (Object o : a) {
  21. @SuppressWarnings("unchecked") E e = (E) o;
  22. //当前新node 的前指针指向 pred
  23. Node<E> newNode = new Node<>(pred, e, null);
  24. //如果pred为空那么first 就是新节点了,否则pred的next是当前节点
  25. if (pred == null)
  26. first = newNode;
  27. else
  28. pred.next = newNode; //这里给挂了.next
  29. // 之后新节点就变成了pred
  30. pred = newNode;
  31. }
  32. // 插入完之后原先index位置上的节点为null 那么last就是最后插入的及诶单 ,否则 给循环添加完节点后的最后一个pred.next置为succ
  33. if (succ == null) {
  34. last = pred;
  35. } else {
  36. pred.next = succ;
  37. succ.prev = pred;
  38. }
  39. // 这样原先的链表就添加完了节点。
  40. size += numNew;
  41. modCount++;
  42. return true;
  43. }

之后我们来看一下get方法

  1. public E get(int index) {
  2. checkElementIndex(index);
  3. //调用了 node方法
  4. return node(index).item;
  5. }
  6. //node方法 获取index位置上的节点
  7. Node<E> node(int index) {
  8. // assert isElementIndex(index);
  9. // 这里进行了一次2分 判断 index 在 size/2的左或者右 如果在左正向遍历,如果再右 反向遍历,提升效率.
  10. if (index < (size >> 1)) {
  11. Node<E> x = first;
  12. for (int i = 0; i < index; i++)
  13. x = x.next;
  14. return x;
  15. } else {
  16. Node<E> x = last;
  17. for (int i = size - 1; i > index; i--)
  18. x = x.prev;
  19. return x;
  20. }
  21. }
  22. //之前的remove方法 同样使用了 node方法
  23. public E remove(int index) {
  24. checkElementIndex(index);
  25. return unlink(node(index));
  26. }

之后是 contains 和 indexof

  1. public boolean contains(Object o) {
  2. return indexOf(o) != -1;
  3. }
  4. // 没什么好说的 遍历查 为空处理
  5. public int indexOf(Object o) {
  6. int index = 0;
  7. if (o == null) {
  8. for (Node<E> x = first; x != null; x = x.next) {
  9. if (x.item == null)
  10. return index;
  11. index++;
  12. }
  13. } else {
  14. for (Node<E> x = first; x != null; x = x.next) {
  15. if (o.equals(x.item))
  16. return index;
  17. index++;
  18. }
  19. }
  20. return -1;
  21. }

之后是一些队列的方法 push pop peek等 很好理解 字面上就能看出来,我这里就不赘述了。
之后我来说一下迭代器 先来看我们最常用的

  1. LinkedList linkedList = new LinkedList();
  2. linkedList.iterator();

这里其实调的是AbstractSequentialList的iterator方法

  1. public Iterator<E> iterator() {
  2. return listIterator();
  3. }
  4. public ListIterator<E> listIterator() {
  5. return listIterator(0);
  6. }
  7. public ListIterator<E> listIterator(final int index) {
  8. rangeCheckForAdd(index);
  9. return new ListItr(index);
  10. }

这里其实AbstractSequentialList中是有ListItr这个类的但是 LinkedList自己又实现了一个内部类 起同样的名字,这里其实new ListItr其实new的是 LinkedList的ListItr,下面我们来看一下他的实现

  1. private class ListItr implements ListIterator<E> {
  2. // 上次返回的node
  3. private Node<E> lastReturned;
  4. //下一个node
  5. private Node<E> next;
  6. //下一个node 的索引值
  7. private int nextIndex;
  8. //操作次数
  9. private int expectedModCount = modCount;
  10. ListItr(int index) {
  11. // assert isPositionIndex(index);
  12. //这里我们一般index = 0 所以next 是first
  13. next = (index == size) ? null : node(index);
  14. nextIndex = index;
  15. }
  16. public boolean hasNext() {
  17. return nextIndex < size;
  18. }
  19. public E next() {
  20. checkForComodification();
  21. if (!hasNext())
  22. throw new NoSuchElementException();
  23. //这里先初始化上次返回的node 也就是这次查询的值
  24. lastReturned = next;
  25. //下一个节点
  26. next = next.next;
  27. //索引++
  28. nextIndex++;
  29. return lastReturned.item;
  30. }
  31. 、、是否有上一个节点
  32. public boolean hasPrevious() {
  33. return nextIndex > 0;
  34. }
  35. //这里能够向前 查询
  36. public E previous() {
  37. checkForComodification();
  38. if (!hasPrevious())
  39. throw new NoSuchElementException();
  40. //这里next 就等于上一个节点
  41. lastReturned = next = (next == null) ? last : next.prev;
  42. nextIndex--;
  43. return lastReturned.item;
  44. }
  45. public int nextIndex() {
  46. return nextIndex;
  47. }
  48. public int previousIndex() {
  49. return nextIndex - 1;
  50. }
  51. public void remove() {
  52. checkForComodification();
  53. if (lastReturned == null)
  54. throw new IllegalStateException();
  55. //remove先记录下上次next返回结果的 下一个节点
  56. Node<E> lastNext = lastReturned.next;
  57. //然后将上次next 的指针去掉
  58. unlink(lastReturned);
  59. if (next==lastReturned)  //这里表示删除的是调用previous()返回的元素。
  60.    next = lastNext; //next被删除,所以next要后移,索引不变。
  61. else
  62. nextIndex--; // 这里表示 调用next()返回的元素 被删了 ,所以要索引--
  63. lastReturned = null; //保证 不能连续删除 必须调用next 或者 previous
  64. expectedModCount++;
  65. }
  66. //后面这两个方法就很简单了
  67. public void set(E e) {
  68. if (lastReturned == null)
  69. throw new IllegalStateException();
  70. checkForComodification();
  71. lastReturned.item = e;
  72. }
  73. public void add(E e) {
  74. checkForComodification();
  75. lastReturned = null;
  76. if (next == null)
  77. linkLast(e);
  78. else
  79. linkBefore(e, next);
  80. nextIndex++;
  81. expectedModCount++;
  82. }
  83. //这里循环操作 action的操作
  84. public void forEachRemaining(Consumer<? super E> action) {
  85. Objects.requireNonNull(action);
  86. while (modCount == expectedModCount && nextIndex < size) {
  87. action.accept(next.item);
  88. lastReturned = next;
  89. next = next.next;
  90. nextIndex++;
  91. }
  92. checkForComodification();
  93. }
  94. //如果有并发操作这个 对象 ,抛出异常
  95. final void checkForComodification() {
  96. if (modCount != expectedModCount)
  97. throw new ConcurrentModificationException();
  98. }
  99. }

jdk1.6后又提供了反向迭代器

  1. /** * @since 1.6 */
  2. public Iterator<E> descendingIterator() {
  3. return new DescendingIterator();
  4. }
  5. /** * 这里 next调previous 除了remove 都是反过来 */
  6. private class DescendingIterator implements Iterator<E> {
  7. private final ListItr itr = new ListItr(size());
  8. public boolean hasNext() {
  9. return itr.hasPrevious();
  10. }
  11. public E next() {
  12. return itr.previous();
  13. }
  14. public void remove() {
  15. itr.remove();
  16. }
  17. }

接着我们看clone

  1. @SuppressWarnings("unchecked")
  2. private LinkedList<E> superClone() {
  3. try {
  4. return (LinkedList<E>) super.clone();
  5. } catch (CloneNotSupportedException e) {
  6. throw new InternalError(e);
  7. }
  8. }
  9. /** * Returns a shallow copy of this {@code LinkedList}. (The elements * themselves are not cloned.) * * @return a shallow copy of this {@code LinkedList} instance */
  10. // 这里很简单,循环,add()
  11. public Object clone() {
  12. LinkedList<E> clone = superClone();
  13. // Put clone into "virgin" state
  14. clone.first = clone.last = null;
  15. clone.size = 0;
  16. clone.modCount = 0;
  17. // Initialize clone with our elements
  18. for (Node<E> x = first; x != null; x = x.next)
  19. clone.add(x.item);
  20. return clone;
  21. }

最后 toArray

  1. public Object[] toArray() {
  2. Object[] result = new Object[size];
  3. int i = 0;
  4. for (Node<E> x = first; x != null; x = x.next)
  5. result[i++] = x.item;
  6. return result;
  7. }
  8. public <T> T[] toArray(T[] a) {
  9. if (a.length < size)
  10. a = (T[])java.lang.reflect.Array.newInstance(
  11. a.getClass().getComponentType(), size);
  12. int i = 0;
  13. Object[] result = a;
  14. for (Node<E> x = first; x != null; x = x.next)
  15. result[i++] = x.item;
  16. /* * <p>如果列表适合指定的数组,并且有空余空间(即, *数组中包含的元素多于列表中的元素,即数组中的元素 *在列表结尾之后立即设置为{@code null}。 *(这对于确定列表的长度非常有用<i>仅</ i>如果 *调用者知道列表不包含任何null元素。) */
  17. if (a.length > size)
  18. a[size] = null;
  19. return a;
  20. }

这里我复制了这个方法的描述 ,但是我感觉这个东西并没什么卵用,因为你无法保证调用这 不含null元素,你只将size索引置为null 后面的还是不为null

  1. @Test
  2. public void test1(){
  3. LinkedList linkedList = new LinkedList();
  4. linkedList.add("1");
  5. linkedList.add("2");
  6. linkedList.add("3");
  7. linkedList.add("4");
  8. System.out.println(linkedList);
  9. String[] strs = { null,null,null,null,"3223","1222","234455"};
  10. Object[] objects = linkedList.toArray(strs);
  11. for(Object o: objects){
  12. System.out.println(o);
  13. }
  14. }

打印结果

  1. [1, 2, 3, 4]
  2. 1
  3. 2
  4. 3
  5. 4
  6. null
  7. 1222
  8. 234455

我这里比较困惑,希望有大神给我解读一下。
LinkedList的源码解析就到这里 jdk1.8新增的并发迭代器Spliterator linkedlist也有实现,我没仔细研究 ,后续补上。

发表评论

表情:
评论列表 (有 0 条评论,530人围观)

还没有评论,来说两句吧...

相关阅读