400-028-6601
建站资讯

网站建设资讯

为你提供网站建设行业资讯、网站优化知识、主机域名邮箱、网站开发常见问题等。

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

前言

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

成都创新互联是一家专注网站建设、网络营销策划、微信小程序定制开发、电子商务建设、网络推广、移动互联开发、研究、服务为一体的技术型公司。公司成立10年以来,已经为上1000家成都纯水机各业的企业公司提供互联网服务。现在,服务的上1000家客户与我们一路同行,见证我们的成长;未来,我们一起分享成功的喜悦。

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

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

一、LinkedList介绍

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

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  
  3.         java.util.AbstractList  
  4.             java.util.AbstractSequentialList  
  5.                 java.util.LinkedList  

实现接口

 
 
 
 
  1. Serializable, Cloneable, Iterable, Collection, Deque, List, Queue  

基本属性

  • 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 LinkedListextends AbstractSequentialList 
  2.     implements List, Deque, Cloneable, java.io.Serializable 
  3. { 
  4.     transient int size = 0;   //LinkedList中存放的元素个数 
  5.     transient Node first;  //头节点 
  6.     transient Node last;   //尾节点 
  7.     //构造方法,创建一个空的列表 
  8.     public LinkedList() { 
  9.     } 
  10.     //将一个指定的集合添加到LinkedList中,先完成初始化,在调用添加操作 
  11.     public LinkedList(Collection c) { 
  12.         this(); 
  13.         addAll(c); 
  14.     } 
  15.     //插入头节点 
  16.     private void linkFirst(E e) { 
  17.         final Node f = first;  //将头节点赋值给f节点 
  18.         //new 一个新的节点,此节点的data = e , pre = null , next - > f  
  19.         final Node newNode = new Node<>(null, e, f); 
  20.         first = newNode; //将新创建的节点地址复制给first 
  21.         if (f == null)  //f == null,表示此时LinkedList为空 
  22.             last = newNode;  //将新创建的节点赋值给last 
  23.         else 
  24.             f.prev = newNode;  //否则f.前驱指向newNode 
  25.         size++; 
  26.         modCount++; 
  27.     } 
  28.     //插入尾节点 
  29.     void linkLast(E e) { 
  30.         final Node l = last;  
  31.         final Node newNode = new Node<>(l, e, null); 
  32.         last = newNode; 
  33.         if (l == null) 
  34.             first = newNode; 
  35.         else 
  36.             l.next = newNode; 
  37.         size++; 
  38.         modCount++; 
  39.     } 
  40.     //在succ节点前插入e节点,并修改各个节点之间的前驱后继 
  41.     void linkBefore(E e, Node succ) { 
  42.         // assert succ != null; 
  43.         final Node pred = succ.prev; 
  44.         final Node newNode = new Node<>(pred, e, succ); 
  45.         succ.prev = newNode; 
  46.         if (pred == null) 
  47.             first = newNode; 
  48.         else 
  49.             pred.next = newNode; 
  50.         size++; 
  51.         modCount++; 
  52.     } 
  53.     //删除头节点 
  54.     private E unlinkFirst(Node f) { 
  55.         // assert f == first && f != null; 
  56.         final E element = f.item; 
  57.         final Node next = f.next; 
  58.         f.item = null; 
  59.         f.next = null; // help GC 
  60.         first = next; 
  61.         if (next == null) 
  62.             last = null; 
  63.         else 
  64.             next.prev = null; 
  65.         size--; 
  66.         modCount++; 
  67.         return element; 
  68.     } 
  69.     //删除尾节点 
  70.     private E unlinkLast(Node l) { 
  71.         // assert l == last && l != null; 
  72.         final E element = l.item; 
  73.         final Node prev = l.prev; 
  74.         l.item = null; 
  75.         l.prev = null; // help GC 
  76.         last = prev; 
  77.         if (prev == null) 
  78.             first = null; 
  79.         else 
  80.             prev.next = null; 
  81.         size--; 
  82.         modCount++; 
  83.         return element; 
  84.     } 
  85.     //删除指定节点 
  86.     E unlink(Node x) { 
  87.         // assert x != null; 
  88.         final E element = x.item; 
  89.         final Node next = x.next;  //获取指定节点的前驱 
  90.         final Node prev = x.prev;  //获取指定节点的后继 
  91.         if (prev == null) { 
  92.             first = next;   //如果前驱为null, 说明此节点为头节点 
  93.         } else { 
  94.             prev.next = next;  //前驱结点的后继节点指向当前节点的后继节点 
  95.             x.prev = null;     //当前节点的前驱置空 
  96.         } 
  97.         if (next == null) {    //如果当前节点的后继节点为null ,说明此节点为尾节点 
  98.             last = prev; 
  99.         } else { 
  100.             next.prev = prev;  //当前节点的后继节点的前驱指向当前节点的前驱节点 
  101.             x.next = null;     //当前节点的后继置空 
  102.         } 
  103.         x.item = null;     //当前节点的元素设置为null ,等待垃圾回收 
  104.         size--; 
  105.         modCount++; 
  106.         return element; 
  107.     } 
  108.     //获取LinkedList中的第一个节点信息 
  109.     public E getFirst() { 
  110.         final Node f = first; 
  111.         if (f == null) 
  112.             throw new NoSuchElementException(); 
  113.         return f.item; 
  114.     } 
  115.     //获取LinkedList中的最后一个节点信息 
  116.     public E getLast() { 
  117.         final Node l = last; 
  118.         if (l == null) 
  119.             throw new NoSuchElementException(); 
  120.         return l.item; 
  121.     } 
  122.     //删除头节点 
  123.     public E removeFirst() { 
  124.         final Node f = first; 
  125.         if (f == null) 
  126.             throw new NoSuchElementException(); 
  127.         return unlinkFirst(f); 
  128.     } 
  129.     //删除尾节点 
  130.     public E removeLast() { 
  131.         final Node l = last; 
  132.         if (l == null) 
  133.             throw new NoSuchElementException(); 
  134.         return unlinkLast(l); 
  135.     } 
  136.     //将添加的元素设置为LinkedList的头节点 
  137.     public void addFirst(E e) { 
  138.         linkFirst(e); 
  139.     } 
  140.     //将添加的元素设置为LinkedList的尾节点 
  141.     public void addLast(E e) { 
  142.         linkLast(e); 
  143.     } 
  144.     //判断LinkedList是否包含指定的元素 
  145.     public boolean contains(Object o) { 
  146.         return indexOf(o) != -1; 
  147.     } 
  148.     //返回List中元素的数量 
  149.     public int size() { 
  150.         return size; 
  151.     } 
  152.     //在LinkedList的尾部添加元素 
  153.     public boolean add(E e) { 
  154.         linkLast(e); 
  155.         return true; 
  156.     } 
  157.     //删除指定的元素 
  158.     public boolean remove(Object o) { 
  159.         if (o == null) { 
  160.             for (Node x = first; x != null; x = x.next) { 
  161.                 if (x.item == null) { 
  162.                     unlink(x); 
  163.                     return true; 
  164.                 } 
  165.             } 
  166.         } else { 
  167.             for (Node x = first; x != null; x = x.next) { 
  168.                 if (o.equals(x.item)) { 
  169.                     unlink(x); 
  170.                     return true; 
  171.                 } 
  172.             } 
  173.         } 
  174.         return false; 
  175.     } 
  176.     //将集合中的元素添加到List中 
  177.     public boolean addAll(Collection c) { 
  178.         return addAll(size, c); 
  179.     } 
  180.     //将集合中的元素全部插入到List中,并从指定的位置开始 
  181.     public boolean addAll(int index, Collection c) { 
  182.         checkPositionIndex(index); 
  183.         Object[] a = c.toArray();  //将集合转化为数组 
  184.         int numNew = a.length;  //获取集合中元素的数量 
  185.         if (numNew == 0)   //集合中没有元素,返回false 
  186.             return false; 
  187.         Node pred, succ; 
  188.         if (index == size) { 
  189.             succ = null; 
  190.             pred = last; 
  191.         } else { 
  192.             succ = node(index); //获取位置为index的结点元素,并赋值给succ 
  193.             pred = succ.prev; 
  194.         } 
  195.         for (Object o : a) {  //遍历数组进行插入操作。修改节点的前驱后继 
  196.             @SuppressWarnings("unchecked") E e = (E) o; 
  197.             Node newNode = new Node<>(pred, e, null); 
  198.             if (pred == null) 
  199.                 first = newNode; 
  200.             else 
  201.                 pred.next = newNode; 
  202.             pred = newNode; 
  203.         } 
  204.         if (succ == null) { 
  205.             last = pred; 
  206.         } else { 
  207.             pred.next = succ; 
  208.             succ.prev = pred; 
  209.         } 
  210.         size += numNew; 
  211.         modCount++; 
  212.         return true; 
  213.     } 
  214.     //删除List中所有的元素 
  215.     public void clear() { 
  216.         // Clearing all of the links between nodes is "unnecessary", but: 
  217.         // - helps a generational GC if the discarded nodes inhabit 
  218.         //   more than one generation 
  219.         // - is sure to free memory even if there is a reachable Iterator 
  220.         for (Node x = first; x != null; ) { 
  221.             Node next = x.next; 
  222.             x.item = null; 
  223.             x.next = null; 
  224.             x.prev = null; 
  225.             x = next; 
  226.         } 
  227.         first = last = null; 
  228.         size = 0; 
  229.         modCount++; 
  230.     } 
  231.     //获取指定位置的元素 
  232.     public E get(int index) { 
  233.         checkElementIndex(index); 
  234.         return node(index).item; 
  235.     } 
  236.     //将节点防止在指定的位置 
  237.     public E set(int index, E element) { 
  238.         checkElementIndex(index); 
  239.         Node x = node(index); 
  240.         E oldVal = x.item; 
  241.         x.item = element; 
  242.         return oldVal; 
  243.     } 
  244.     //将节点放置在指定的位置 
  245.     public void add(int index, E element) { 
  246.         checkPositionIndex(index); 
  247.         if (index == size) 
  248.             linkLast(element); 
  249.         else 
  250.             linkBefore(element, node(index)); 
  251.     } 
  252.     //删除指定位置的元素 
  253.     public E remove(int index) { 
  254.         checkElementIndex(index); 
  255.         return unlink(node(index)); 
  256.     } 
  257.     //判断索引是否合法 
  258.     private boolean isElementIndex(int index) { 
  259.         return index >= 0 && index < size; 
  260.     } 
  261.     //判断位置是否合法 
  262.     private boolean isPositionIndex(int index) { 
  263.         return index >= 0 && index <= size; 
  264.     } 
  265.     //索引溢出信息 
  266.     private String outOfBoundsMsg(int index) { 
  267.         return "Index: "+index+", Size: "+size; 
  268.     } 
  269.     //检查节点是否合法 
  270.     private void checkElementIndex(int index) { 
  271.         if (!isElementIndex(index)) 
  272.             throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); 
  273.     } 
  274.     //检查位置是否合法 
  275.     private void checkPositionIndex(int index) { 
  276.         if (!isPositionIndex(index)) 
  277.             throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); 
  278.     } 
  279.     //返回指定位置的节点信息 
  280.     //LinkedList无法随机访问,只能通过遍历的方式找到相应的节点 
  281.     //为了提高效率,当前位置首先和元素数量的中间位置开始判断,小于中间位置, 
  282.     //从头节点开始遍历,大于中间位置从尾节点开始遍历 
  283.     Node node(int index) { 
  284.         // assert isElementIndex(index); 
  285.         if (index < (size >> 1)) { 
  286.             Node x = first; 
  287.             for (int i = 0; i < index; i++) 
  288.                 x = x.next; 
  289.             return x; 
  290.         } else { 
  291.             Node x = last; 
  292.             for (int i = size - 1; i > index; i--) 
  293.                 x = x.prev; 
  294.             return x; 
  295.         } 
  296.     } 
  297.     //返回第一次出现指定元素的位置 
  298.     public int indexOf(Object o) { 
  299.         int index = 0; 
  300.         if (o == null) { 
  301.             for (Node x = first; x != null; x = x.next) { 
  302.                 if (x.item == null) 
  303.                     return index; 
  304.                 index++; 
  305.             } 
  306.         } else { 
  307.             for (Node x = first; x != null; x = x.next) { 
  308.                 if (o.equals(x.item)) 
  309.                     return index; 
  310.                 index++; 
  311.             } 
  312.         } 
  313.         return -1; 
  314.     } 
  315.     //返回最后一次出现元素的位置 
  316.     public int lastIndexOf(Object o) { 
  317.         int index = size; 
  318.         if (o == null) { 
  319.             for (Node x = last; x != null; x = x.prev) { 
  320.                 index--; 
  321.                 if (x.item == null) 
  322.                     return index; 
  323.             } 
  324.         } else { 
  325.             for (Node x = last; x != null; x = x.prev) { 
  326.                 index--; 
  327.                 if (o.equals(x.item)) 
  328.                     return index; 
  329.             } 
  330.         } 
  331.         return -1; 
  332.     } 
  333.     //弹出第一个元素的值 
  334.     public E peek() { 
  335.         final Node f = first; 
  336.         return (f == null) ? null : f.item; 
  337.     } 
  338.     //获取第一个元素 
  339.     public E element() { 
  340.         return getFirst(); 
  341.     } 
  342.     //弹出第一元素,并删除 
  343.     public E poll() { 
  344.         final Node f = first; 
  345.         return (f == null) ? null : unlinkFirst(f); 
  346.     } 
  347.     //删除第一个元素 
  348.     public E remove() { 
  349.         return removeFirst(); 
  350.     } 
  351.     //添加到尾部 
  352.     public boolean offer(E e) { 
  353.         return add(e); 
  354.     } 
  355.     //添加到头部 
  356.     public boolean offerFirst(E e) { 
  357.         addFirst(e); 
  358.         return true; 
  359.     } 
  360.     //插入到最后一个元素 
  361.     public boolean offerLast(E e) { 
  362.         addLast(e); 
  363.         return true; 
  364.     } 
  365.     //队列操作 
  366.     //尝试弹出第一个元素,但是不删除元素 
  367.     public E peekFirst() { 
  368.         final Node f = first; 
  369.         return (f == null) ? null : f.item; 
  370.      } 
  371.     //队列操作 
  372.     //尝试弹出最后一个元素,不删除 
  373.     public E peekLast() { 
  374.         final Node l = last; 
  375.         return (l == null) ? null : l.item; 
  376.     } 
  377.     //弹出第一个元素,并删除 
  378.     public E pollFirst() { 
  379.         final Node f = first; 
  380.         return (f == null) ? null : unlinkFirst(f); 
  381.     } 
  382.     //弹出最后一个元素,并删除 
  383.     public E pollLast() { 
  384.         final Node l = last; 
  385.         return (l == null) ? null : unlinkLast(l); 
  386.     } 
  387.     //如队列,添加到头部 
  388.     public void push(E e) { 
  389.         addFirst(e); 
  390.     } 
  391.     //出队列删除第一个节点 
  392.     public E pop() { 
  393.         return removeFirst(); 
  394.     } 
  395.    //删除指定元素第一次出现的位置 
  396.     public boolean removeFirstOccurrence(Object o) { 
  397.         return remove(o); 
  398.     } 
  399.     //删除指定元素最后一次出现的位置 
  400.     public boolean removeLastOccurrence(Object o) { 
  401.         if (o == null) { 
  402.             for (Node x = last; x != null; x = x.prev) { 
  403.                 if (x.item == null) { 
  404.                     unlink(x); 
  405.                     return true; 
  406.                 } 
  407.             } 
  408.         } else { 
  409.             for (Node x = last; x != null; x = x.prev) { 
  410.  
    文章标题:数据结构之LinkedList底层实现和原理详解
    网站路径:http://hnjierui.cn/article/cdicepo.html

其他资讯