数据结构之LinkedList底层实现和原理详解

移动开发 Android
日常开发中,集合是我们经常用到的一种数据结构,当然,集合也并不是一种,也没有所谓的最好的集合,只有最适合的;今天我们就来聊聊LinkedList底层实现和原理。

[[420549]]

前言

日常开发中,集合是我们经常用到的一种数据结构,当然,集合也并不是一种,也没有所谓的最好的集合,只有最适合的;

当然作为高级程序员,我们不仅仅要会用,还要了解其中的原理;

今天我们就来聊聊LinkedList底层实现和原理

一、LinkedList介绍

  1. public class LinkedList<E> 
  2.     extends AbstractSequentialList<E> 
  3.     implements List<E>, Deque<E>, Cloneable, java.io.Serializable 
  4.     //长度 
  5.     transient int size = 0; 
  6.     //指向头结点 
  7.     transient Node<E> first
  8.     //指向尾结点 
  9.     transient Node<E> last

1、LinkedList概述

LinkedList同时实现了List接口和Deque对口,也就是收它既可以看作一个顺序容器,又可以看作一个队列(Queue),同时又可以看作一个栈(stack);

这样看来,linkedList简直就是无敌的,当你需要使用栈或者队列时,可以考虑用LinkedList,一方面是因为Java官方已经声明不建议使用Stack类,更遗憾的是,Java里根本没有一个叫做Queue的类(只是一个接口的名字);

关于栈或队列,现在首选是ArrayDeque,它有着比LinkedList(当作栈或队列使用时)更好的性能;

LinkedList的实现方式决定了所有跟下表有关的操作都是线性时间,而在首段或者末尾删除元素只需要常数时间。为追求效率LinkedList没有实现同步(synchronized),如果需要多个线程并发访问,可以先采用Collections.synchronizedList()方法对其进行包装

2、数据结构

继承关系

  1. java.lang.Object  
  2.     java.util.AbstractCollection<E>  
  3.         java.util.AbstractList<E>  
  4.             java.util.AbstractSequentialList<E>  
  5.                 java.util.LinkedList<E>  

实现接口

  1. Serializable, Cloneable, Iterable<E>, Collection<E>, Deque<E>, List<E>, Queue<E>  

基本属性

  • transient int size = 0; //LinkedList中存放的元素个数
  • transient Node first; //头节点
  • transient Node last; //尾节点
  • Collection 接口:Collection接口是所有集合类的根节点,Collection表示一种规则,所有实现了Collection接口的类遵循这种规则

继承的类与实现的接口

  • List 接口:List是Collection的子接口,它是一个元素有序(按照插入的顺序维护元素顺序)、可重复、可以为null的集合
  • AbstractCollection 类:Collection接口的骨架实现类,最小化实现了Collection接口所需要实现的工作量
  • AbstractList 类:List接口的骨架实现类,最小化实现了List接口所需要实现的工作量
  • Cloneable 接口:实现了该接口的类可以显示的调用Object.clone()方法,合法的对该类实例进行字段复制,如果没有实现Cloneable接口的实例上调用Obejct.clone()方法,会抛出CloneNotSupportException异常。正常情况下,实现了Cloneable接口的类会以公共方法重写Object.clone()
  • Serializable 接口:实现了该接口标示了类可以被序列化和反序列化,具体的 查询序列化详解
  • Deque 接口:Deque定义了一个线性Collection,支持在两端插入和删除元素,Deque实际是“double ended queue(双端队列)”的简称,大多数Deque接口的实现都不会限制元素的数量,但是这个队列既支持有容量限制的实现,也支持没有容量限制的实现,比如LinkedList就是有容量限制的实现,其最大的容量为Integer.MAX_VALUE
  • AbstractSequentialList 类:提供了List接口的骨干实现,最大限度地减少了实现受“连续访问”数据存储(如链表)支持的此接口所需的工作,对于随机访问数据(如数组),应该优先使用 AbstractList,而不是使用AbstractSequentailList类

二、底层源码分析

LinkedList是通过双向链表去实现的,既然是链表实现那么它的随机访问效率比ArrayList要低,顺序访问的效率要比较的高。每个节点都有一个前驱(之前前面节点的指针)和一个后继(指向后面节点的指针)

效果如下图:

源码标注如下:

  1. public class LinkedList<E>extends AbstractSequentialList<E> 
  2.     implements List<E>, Deque<E>, Cloneable, java.io.Serializable 
  3.     transient int size = 0;   //LinkedList中存放的元素个数 
  4.     transient Node<E> first;  //头节点 
  5.     transient Node<E> last;   //尾节点 
  6.     //构造方法,创建一个空的列表 
  7.     public LinkedList() { 
  8.     } 
  9.     //将一个指定的集合添加到LinkedList中,先完成初始化,在调用添加操作 
  10.     public LinkedList(Collection<? extends E> c) { 
  11.         this(); 
  12.         addAll(c); 
  13.     } 
  14.     //插入头节点 
  15.     private void linkFirst(E e) { 
  16.         final Node<E> f = first;  //将头节点赋值给f节点 
  17.         //new 一个新的节点,此节点的data = e , pre = null , next - > f  
  18.         final Node<E> newNode = new Node<>(null, e, f); 
  19.         first = newNode; //将新创建的节点地址复制给first 
  20.         if (f == null)  //f == null,表示此时LinkedList为空 
  21.             last = newNode;  //将新创建的节点赋值给last 
  22.         else 
  23.             f.prev = newNode;  //否则f.前驱指向newNode 
  24.         size++; 
  25.         modCount++; 
  26.     } 
  27.     //插入尾节点 
  28.     void linkLast(E e) { 
  29.         final Node<E> l = last;  
  30.         final Node<E> newNode = new Node<>(l, e, null); 
  31.         last = newNode; 
  32.         if (l == null
  33.             first = newNode; 
  34.         else 
  35.             l.next = newNode; 
  36.         size++; 
  37.         modCount++; 
  38.     } 
  39.     //在succ节点前插入e节点,并修改各个节点之间的前驱后继 
  40.     void linkBefore(E e, Node<E> succ) { 
  41.         // assert succ != null
  42.         final Node<E> pred = succ.prev; 
  43.         final Node<E> newNode = new Node<>(pred, e, succ); 
  44.         succ.prev = newNode; 
  45.         if (pred == null
  46.             first = newNode; 
  47.         else 
  48.             pred.next = newNode; 
  49.         size++; 
  50.         modCount++; 
  51.     } 
  52.     //删除头节点 
  53.     private E unlinkFirst(Node<E> f) { 
  54.         // assert f == first && f != null
  55.         final E element = f.item; 
  56.         final Node<E> next = f.next
  57.         f.item = null
  58.         f.next = null; // help GC 
  59.         first = next
  60.         if (next == null
  61.             last = null
  62.         else 
  63.             next.prev = null
  64.         size--; 
  65.         modCount++; 
  66.         return element; 
  67.     } 
  68.     //删除尾节点 
  69.     private E unlinkLast(Node<E> l) { 
  70.         // assert l == last && l != null
  71.         final E element = l.item; 
  72.         final Node<E> prev = l.prev; 
  73.         l.item = null
  74.         l.prev = null; // help GC 
  75.         last = prev; 
  76.         if (prev == null
  77.             first = null
  78.         else 
  79.             prev.next = null
  80.         size--; 
  81.         modCount++; 
  82.         return element; 
  83.     } 
  84.     //删除指定节点 
  85.     E unlink(Node<E> x) { 
  86.         // assert x != null
  87.         final E element = x.item; 
  88.         final Node<E> next = x.next;  //获取指定节点的前驱 
  89.         final Node<E> prev = x.prev;  //获取指定节点的后继 
  90.         if (prev == null) { 
  91.             first = next;   //如果前驱为null, 说明此节点为头节点 
  92.         } else { 
  93.             prev.next = next;  //前驱结点的后继节点指向当前节点的后继节点 
  94.             x.prev = null;     //当前节点的前驱置空 
  95.         } 
  96.         if (next == null) {    //如果当前节点的后继节点为null ,说明此节点为尾节点 
  97.             last = prev; 
  98.         } else { 
  99.             next.prev = prev;  //当前节点的后继节点的前驱指向当前节点的前驱节点 
  100.             x.next = null;     //当前节点的后继置空 
  101.         } 
  102.         x.item = null;     //当前节点的元素设置为null ,等待垃圾回收 
  103.         size--; 
  104.         modCount++; 
  105.         return element; 
  106.     } 
  107.     //获取LinkedList中的第一个节点信息 
  108.     public E getFirst() { 
  109.         final Node<E> f = first
  110.         if (f == null
  111.             throw new NoSuchElementException(); 
  112.         return f.item; 
  113.     } 
  114.     //获取LinkedList中的最后一个节点信息 
  115.     public E getLast() { 
  116.         final Node<E> l = last
  117.         if (l == null
  118.             throw new NoSuchElementException(); 
  119.         return l.item; 
  120.     } 
  121.     //删除头节点 
  122.     public E removeFirst() { 
  123.         final Node<E> f = first
  124.         if (f == null
  125.             throw new NoSuchElementException(); 
  126.         return unlinkFirst(f); 
  127.     } 
  128.     //删除尾节点 
  129.     public E removeLast() { 
  130.         final Node<E> l = last
  131.         if (l == null
  132.             throw new NoSuchElementException(); 
  133.         return unlinkLast(l); 
  134.     } 
  135.     //将添加的元素设置为LinkedList的头节点 
  136.     public void addFirst(E e) { 
  137.         linkFirst(e); 
  138.     } 
  139.     //将添加的元素设置为LinkedList的尾节点 
  140.     public void addLast(E e) { 
  141.         linkLast(e); 
  142.     } 
  143.     //判断LinkedList是否包含指定的元素 
  144.     public boolean contains(Object o) { 
  145.         return indexOf(o) != -1; 
  146.     } 
  147.     //返回List中元素的数量 
  148.     public int size() { 
  149.         return size
  150.     } 
  151.     //在LinkedList的尾部添加元素 
  152.     public boolean add(E e) { 
  153.         linkLast(e); 
  154.         return true
  155.     } 
  156.     //删除指定的元素 
  157.     public boolean remove(Object o) { 
  158.         if (o == null) { 
  159.             for (Node<E> x = first; x != null; x = x.next) { 
  160.                 if (x.item == null) { 
  161.                     unlink(x); 
  162.                     return true
  163.                 } 
  164.             } 
  165.         } else { 
  166.             for (Node<E> x = first; x != null; x = x.next) { 
  167.                 if (o.equals(x.item)) { 
  168.                     unlink(x); 
  169.                     return true
  170.                 } 
  171.             } 
  172.         } 
  173.         return false
  174.     } 
  175.     //将集合中的元素添加到List中 
  176.     public boolean addAll(Collection<? extends E> c) { 
  177.         return addAll(size, c); 
  178.     } 
  179.     //将集合中的元素全部插入到List中,并从指定的位置开始 
  180.     public boolean addAll(int index, Collection<? extends E> c) { 
  181.         checkPositionIndex(index); 
  182.         Object[] a = c.toArray();  //将集合转化为数组 
  183.         int numNew = a.length;  //获取集合中元素的数量 
  184.         if (numNew == 0)   //集合中没有元素,返回false 
  185.             return false
  186.         Node<E> pred, succ; 
  187.         if (index == size) { 
  188.             succ = null
  189.             pred = last
  190.         } else { 
  191.             succ = node(index); //获取位置为index的结点元素,并赋值给succ 
  192.             pred = succ.prev; 
  193.         } 
  194.         for (Object o : a) {  //遍历数组进行插入操作。修改节点的前驱后继 
  195.             @SuppressWarnings("unchecked") E e = (E) o; 
  196.             Node<E> newNode = new Node<>(pred, e, null); 
  197.             if (pred == null
  198.                 first = newNode; 
  199.             else 
  200.                 pred.next = newNode; 
  201.             pred = newNode; 
  202.         } 
  203.         if (succ == null) { 
  204.             last = pred; 
  205.         } else { 
  206.             pred.next = succ; 
  207.             succ.prev = pred; 
  208.         } 
  209.         size += numNew; 
  210.         modCount++; 
  211.         return true
  212.     } 
  213.     //删除List中所有的元素 
  214.     public void clear() { 
  215.         // Clearing all of the links between nodes is "unnecessary", but: 
  216.         // - helps a generational GC if the discarded nodes inhabit 
  217.         //   more than one generation 
  218.         // - is sure to free memory even if there is a reachable Iterator 
  219.         for (Node<E> x = first; x != null; ) { 
  220.             Node<E> next = x.next
  221.             x.item = null
  222.             x.next = null
  223.             x.prev = null
  224.             x = next
  225.         } 
  226.         first = last = null
  227.         size = 0; 
  228.         modCount++; 
  229.     } 
  230.     //获取指定位置的元素 
  231.     public E get(int index) { 
  232.         checkElementIndex(index); 
  233.         return node(index).item; 
  234.     } 
  235.     //将节点防止在指定的位置 
  236.     public E set(int index, E element) { 
  237.         checkElementIndex(index); 
  238.         Node<E> x = node(index); 
  239.         E oldVal = x.item; 
  240.         x.item = element; 
  241.         return oldVal; 
  242.     } 
  243.     //将节点放置在指定的位置 
  244.     public void add(int index, E element) { 
  245.         checkPositionIndex(index); 
  246.         if (index == size
  247.             linkLast(element); 
  248.         else 
  249.             linkBefore(element, node(index)); 
  250.     } 
  251.     //删除指定位置的元素 
  252.     public E remove(int index) { 
  253.         checkElementIndex(index); 
  254.         return unlink(node(index)); 
  255.     } 
  256.     //判断索引是否合法 
  257.     private boolean isElementIndex(int index) { 
  258.         return index >= 0 && index < size
  259.     } 
  260.     //判断位置是否合法 
  261.     private boolean isPositionIndex(int index) { 
  262.         return index >= 0 && index <= size
  263.     } 
  264.     //索引溢出信息 
  265.     private String outOfBoundsMsg(int index) { 
  266.         return "Index: "+index+", Size: "+size
  267.     } 
  268.     //检查节点是否合法 
  269.     private void checkElementIndex(int index) { 
  270.         if (!isElementIndex(index)) 
  271.             throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); 
  272.     } 
  273.     //检查位置是否合法 
  274.     private void checkPositionIndex(int index) { 
  275.         if (!isPositionIndex(index)) 
  276.             throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); 
  277.     } 
  278.     //返回指定位置的节点信息 
  279.     //LinkedList无法随机访问,只能通过遍历的方式找到相应的节点 
  280.     //为了提高效率,当前位置首先和元素数量的中间位置开始判断,小于中间位置, 
  281.     //从头节点开始遍历,大于中间位置从尾节点开始遍历 
  282.     Node<E> node(int index) { 
  283.         // assert isElementIndex(index); 
  284.         if (index < (size >> 1)) { 
  285.             Node<E> x = first
  286.             for (int i = 0; i < index; i++) 
  287.                 x = x.next
  288.             return x; 
  289.         } else { 
  290.             Node<E> x = last
  291.             for (int i = size - 1; i > index; i--) 
  292.                 x = x.prev; 
  293.             return x; 
  294.         } 
  295.     } 
  296.     //返回第一次出现指定元素的位置 
  297.     public int indexOf(Object o) { 
  298.         int index = 0; 
  299.         if (o == null) { 
  300.             for (Node<E> x = first; x != null; x = x.next) { 
  301.                 if (x.item == null
  302.                     return index
  303.                 index++; 
  304.             } 
  305.         } else { 
  306.             for (Node<E> x = first; x != null; x = x.next) { 
  307.                 if (o.equals(x.item)) 
  308.                     return index
  309.                 index++; 
  310.             } 
  311.         } 
  312.         return -1; 
  313.     } 
  314.     //返回最后一次出现元素的位置 
  315.     public int lastIndexOf(Object o) { 
  316.         int index = size
  317.         if (o == null) { 
  318.             for (Node<E> x = last; x != null; x = x.prev) { 
  319.                 index--; 
  320.                 if (x.item == null
  321.                     return index
  322.             } 
  323.         } else { 
  324.             for (Node<E> x = last; x != null; x = x.prev) { 
  325.                 index--; 
  326.                 if (o.equals(x.item)) 
  327.                     return index
  328.             } 
  329.         } 
  330.         return -1; 
  331.     } 
  332.     //弹出第一个元素的值 
  333.     public E peek() { 
  334.         final Node<E> f = first
  335.         return (f == null) ? null : f.item; 
  336.     } 
  337.     //获取第一个元素 
  338.     public E element() { 
  339.         return getFirst(); 
  340.     } 
  341.     //弹出第一元素,并删除 
  342.     public E poll() { 
  343.         final Node<E> f = first
  344.         return (f == null) ? null : unlinkFirst(f); 
  345.     } 
  346.     //删除第一个元素 
  347.     public E remove() { 
  348.         return removeFirst(); 
  349.     } 
  350.     //添加到尾部 
  351.     public boolean offer(E e) { 
  352.         return add(e); 
  353.     } 
  354.     //添加到头部 
  355.     public boolean offerFirst(E e) { 
  356.         addFirst(e); 
  357.         return true
  358.     } 
  359.     //插入到最后一个元素 
  360.     public boolean offerLast(E e) { 
  361.         addLast(e); 
  362.         return true
  363.     } 
  364.     //队列操作 
  365.     //尝试弹出第一个元素,但是不删除元素 
  366.     public E peekFirst() { 
  367.         final Node<E> f = first
  368.         return (f == null) ? null : f.item; 
  369.      } 
  370.     //队列操作 
  371.     //尝试弹出最后一个元素,不删除 
  372.     public E peekLast() { 
  373.         final Node<E> l = last
  374.         return (l == null) ? null : l.item; 
  375.     } 
  376.     //弹出第一个元素,并删除 
  377.     public E pollFirst() { 
  378.         final Node<E> f = first
  379.         return (f == null) ? null : unlinkFirst(f); 
  380.     } 
  381.     //弹出最后一个元素,并删除 
  382.     public E pollLast() { 
  383.         final Node<E> l = last
  384.         return (l == null) ? null : unlinkLast(l); 
  385.     } 
  386.     //如队列,添加到头部 
  387.     public void push(E e) { 
  388.         addFirst(e); 
  389.     } 
  390.     //出队列删除第一个节点 
  391.     public E pop() { 
  392.         return removeFirst(); 
  393.     } 
  394.    //删除指定元素第一次出现的位置 
  395.     public boolean removeFirstOccurrence(Object o) { 
  396.         return remove(o); 
  397.     } 
  398.     //删除指定元素最后一次出现的位置 
  399.     public boolean removeLastOccurrence(Object o) { 
  400.         if (o == null) { 
  401.             for (Node<E> x = last; x != null; x = x.prev) { 
  402.                 if (x.item == null) { 
  403.                     unlink(x); 
  404.                     return true
  405.                 } 
  406.             } 
  407.         } else { 
  408.             for (Node<E> x = last; x != null; x = x.prev) { 
  409.                 if (o.equals(x.item)) { 
  410.                     unlink(x); 
  411.                     return true
  412.                 } 
  413.             } 
  414.         } 
  415.         return false
  416.     } 
  417.     //遍历方法 
  418.     public ListIterator<E> listIterator(int index) { 
  419.         checkPositionIndex(index); 
  420.         return new ListItr(index); 
  421.     } 
  422.     //内部类,实现ListIterator接口 
  423.     private class ListItr implements ListIterator<E> { 
  424.         private Node<E> lastReturned = null
  425.         private Node<E> next
  426.         private int nextIndex; 
  427.         private int expectedModCount = modCount; 
  428.         ListItr(int index) { 
  429.             // assert isPositionIndex(index); 
  430.             next = (index == size) ? null : node(index); 
  431.             nextIndex = index
  432.         } 
  433.         public boolean hasNext() { 
  434.             return nextIndex < size
  435.         } 
  436.         public E next() { 
  437.             checkForComodification(); 
  438.             if (!hasNext()) 
  439.                 throw new NoSuchElementException(); 
  440.             lastReturned = next
  441.             next = next.next
  442.             nextIndex++; 
  443.             return lastReturned.item; 
  444.         } 
  445.         public boolean hasPrevious() { 
  446.             return nextIndex > 0; 
  447.         } 
  448.         public E previous() { 
  449.             checkForComodification(); 
  450.             if (!hasPrevious()) 
  451.                 throw new NoSuchElementException(); 
  452.             lastReturned = next = (next == null) ? last : next.prev; 
  453.             nextIndex--; 
  454.             return lastReturned.item; 
  455.         } 
  456.         public int nextIndex() { 
  457.             return nextIndex; 
  458.         } 
  459.         public int previousIndex() { 
  460.             return nextIndex - 1; 
  461.         } 
  462.         public void remove() { 
  463.             checkForComodification(); 
  464.             if (lastReturned == null
  465.                 throw new IllegalStateException(); 
  466.             Node<E> lastNext = lastReturned.next
  467.             unlink(lastReturned); 
  468.             if (next == lastReturned) 
  469.                 next = lastNext; 
  470.             else 
  471.                 nextIndex--; 
  472.             lastReturned = null
  473.             expectedModCount++; 
  474.         } 
  475.         public void set(E e) { 
  476.             if (lastReturned == null
  477.                 throw new IllegalStateException(); 
  478.             checkForComodification(); 
  479.             lastReturned.item = e; 
  480.         } 
  481.         public void add(E e) { 
  482.             checkForComodification(); 
  483.             lastReturned = null
  484.             if (next == null
  485.                 linkLast(e); 
  486.             else 
  487.                 linkBefore(e, next); 
  488.             nextIndex++; 
  489.             expectedModCount++; 
  490.         } 
  491.         final void checkForComodification() { 
  492.             if (modCount != expectedModCount) 
  493.                 throw new ConcurrentModificationException(); 
  494.         } 
  495.     } 
  496.     //静态内部类,创建节点 
  497.     private static class Node<E> { 
  498.         E item; 
  499.         Node<E> next
  500.         Node<E> prev; 
  501.         Node(Node<E> prev, E element, Node<E> next) { 
  502.             this.item = element; 
  503.             this.next = next
  504.             this.prev = prev; 
  505.         } 
  506.     } 
  507.     /** 
  508.      * @since 1.6 
  509.      */ 
  510.     public Iterator<E> descendingIterator() { 
  511.         return new DescendingIterator(); 
  512.     } 
  513.     /** 
  514.      * Adapter to provide descending iterators via ListItr.previous 
  515.      */ 
  516.     private class DescendingIterator implements Iterator<E> { 
  517.         private final ListItr itr = new ListItr(size()); 
  518.         public boolean hasNext() { 
  519.             return itr.hasPrevious(); 
  520.         } 
  521.         public E next() { 
  522.             return itr.previous(); 
  523.         } 
  524.         public void remove() { 
  525.             itr.remove(); 
  526.         } 
  527.     } 
  528.     @SuppressWarnings("unchecked"
  529.     private LinkedList<E> superClone() { 
  530.         try { 
  531.             return (LinkedList<E>) super.clone(); 
  532.         } catch (CloneNotSupportedException e) { 
  533.             throw new InternalError(); 
  534.         } 
  535.     } 
  536.     /** 
  537.      * Returns a shallow copy of this {@code LinkedList}. (The elements 
  538.      * themselves are not cloned.) 
  539.      * 
  540.      * @return a shallow copy of this {@code LinkedList} instance 
  541.      */ 
  542.     public Object clone() { 
  543.         LinkedList<E> clone = superClone(); 
  544.         // Put clone into "virgin" state 
  545.         clone.first = clone.last = null
  546.         clone.size = 0; 
  547.         clone.modCount = 0; 
  548.         // Initialize clone with our elements 
  549.         for (Node<E> x = first; x != null; x = x.next
  550.             clone.add(x.item); 
  551.         return clone; 
  552.     } 
  553.     public Object[] toArray() { 
  554.         Object[] result = new Object[size]; 
  555.         int i = 0; 
  556.         for (Node<E> x = first; x != null; x = x.next
  557.             result[i++] = x.item; 
  558.         return result; 
  559.     } 
  560.     @SuppressWarnings("unchecked"
  561.     public <T> T[] toArray(T[] a) { 
  562.         if (a.length < size
  563.             a = (T[])java.lang.reflect.Array.newInstance( 
  564.                                 a.getClass().getComponentType(), size); 
  565.         int i = 0; 
  566.         Object[] result = a; 
  567.         for (Node<E> x = first; x != null; x = x.next
  568.             result[i++] = x.item; 
  569.         if (a.length > size
  570.             a[size] = null
  571.         return a; 
  572.     } 
  573.     private static final long serialVersionUID = 876323262645176354L; 
  574.     //将对象写入到输出流中 
  575.     private void writeObject(java.io.ObjectOutputStream s) 
  576.         throws java.io.IOException { 
  577.         // Write out any hidden serialization magic 
  578.         s.defaultWriteObject(); 
  579.         // Write out size 
  580.         s.writeInt(size); 
  581.         // Write out all elements in the proper order
  582.         for (Node<E> x = first; x != null; x = x.next
  583.             s.writeObject(x.item); 
  584.     } 
  585.     //从输入流中将对象读出 
  586.     @SuppressWarnings("unchecked"
  587.     private void readObject(java.io.ObjectInputStream s) 
  588.         throws java.io.IOException, ClassNotFoundException { 
  589.         // Read in any hidden serialization magic 
  590.         s.defaultReadObject(); 
  591.         // Read in size 
  592.         int size = s.readInt(); 
  593.         // Read in all elements in the proper order
  594.         for (int i = 0; i < size; i++) 
  595.             linkLast((E)s.readObject()); 
  596.     } 

1、构造方法

  1. LinkedList()  
  2. LinkedList(Collection<? extends E> c) 

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

2、添加节点

  1. public boolean add(E e) { 
  2.      linkLast(e); 
  3.      return true
  4. void linkLast(E e) { 
  5.      final Node<E> l = last
  6.      final Node<E> newNode = new Node<>(l, e, null); 
  7.      last = newNode; 
  8.      if (l == null
  9.          first = newNode; 
  10.      else 
  11.           l.next = newNode; 
  12.      size++; 
  13.      modCount++; 

通过源码可以看出添加的过程如下:

  • 记录当前末尾节点,通过构造另外一个指向末尾节点的指针l
  • 产生新的节点:注意的是由于是添加在链表的末尾,next是为null的
  • last指向新的节点
  • 这里有个判断,我的理解是判断是否为第一个元素(当l==null时,表示链表中是没有节点的),
  • 那么就很好理解这个判断了,如果是第一节点,则使用first指向这个节点,若不是则当前节点的next指向新增的节点
  • size增加:在上面提到的LinkedList["A","B","C"]中添加元素“D”,过程大致如图:

3、删除节点

LinkedList中提供了两个方法删除节点

  1. //方法1.删除指定索引上的节点 
  2. public E remove(int index) { 
  3.     //检查索引是否正确 
  4.     checkElementIndex(index); 
  5.     //这里分为两步,第一通过索引定位到节点,第二删除节点 
  6.     return unlink(node(index)); 
  7. //方法2.删除指定值的节点 
  8. public boolean remove(Object o) { 
  9.     //判断删除的元素是否为null 
  10.     if (o == null) { 
  11.         //若是null遍历删除 
  12.         for (Node<E> x = first; x != null; x = x.next) { 
  13.             if (x.item == null) { 
  14.                 unlink(x); 
  15.                 return true
  16.             } 
  17.         } 
  18.     } else { 
  19.         //若不是遍历删除  
  20.         for (Node<E> x = first; x != null; x = x.next) { 
  21.             if (o.equals(x.item)) { 
  22.                 unlink(x); 
  23.                 return true
  24.             } 
  25.         } 
  26.     } 
  27.     return false

通过源码可以看出两个方法都是通过unlink()删除

  • 获取到需要删除元素当前的值,指向它前一个节点的引用,以及指向它后一个节点的引用。
  • 判断删除的是否为第一个节点,若是则first向后移动,若不是则将当前节点的前一个节点next指向当前节点的后一个节点
  • 判断删除的是否为最后一个节点,若是则last向前移动,若不是则将当前节点的后一个节点的prev指向当前节点的前一个节点
  • 将当前节点的值置为null
  • size减少并返回删除节点的值

三、ArrayList和LinkedList区别

1.底层实现:ArrayList内部是数组实现,而LinkedList内部实现是双向链表结构;

2.接口实现:都实现了List接口,都是线性列表的实现,ArrayList实现了RandomAccess可以支持随机元素访问,而LinkedList实现了Deque可以当做队列使用;

3.性能:新增、删除元素时ArrayList需要使用到拷贝原数组,而LinkedList只需移动指针,查找元素 ArrayList支持随机元素访问,而LinkedList只能一个节点的去遍历;

4、线程安全:都是线程不安全的;

5、LinkedList下插入、删除是性能优于ArrayList,这是由于插入、删除元素时ArrayList中需要额外的开销去移动、拷贝元素(但是使用removeElements2方法所示去遍历删除是速度异常的快,这种方式的做法是从末尾开始删除,不存在移动、拷贝元素,从而速度非常快);

6.ArrayList在查询元素的性能上要由于LinkedList;

总结

LinkedList是一个功能很强大的类,可以被当作List集合,双端队列和栈来使用;LinkedList底层使用链表来保存集合中的元素,因此随机访问的性能较差,但是插入删除时性能非常的出色;

 本文转载自微信公众号「Android开发编程」

 

责任编辑:姜华 来源: Android开发编程
相关推荐

2021-08-29 07:41:48

数据HashMap底层

2019-10-29 08:59:16

Redis底层数据

2020-05-20 09:55:42

Git底层数据

2022-12-19 08:00:00

SpringBootWeb开发

2023-06-08 07:25:56

数据库索引数据结构

2019-09-27 08:53:47

Redis数据C语言

2023-09-22 11:17:50

红黑树结构数据结构

2023-07-11 08:00:00

2023-03-06 08:40:43

RedisListJava

2019-09-18 08:31:47

数据结构设计

2023-09-15 08:14:48

HashMap负载因子

2019-04-17 15:35:37

Redis数据库数据结构

2020-03-20 10:47:51

Redis数据库字符串

2019-06-21 15:20:05

Redis数据结构数据库

2023-07-17 08:02:44

ZuulIO反应式

2023-09-13 08:08:41

Redis消息队列

2019-06-12 22:51:57

Redis软件开发

2024-01-05 09:00:00

SpringMVC软件

2019-08-13 09:40:55

数据结构算法JavasCript

2023-04-11 08:00:56

Redis类型编码
点赞
收藏

51CTO技术栈公众号