一篇文章搞定ArrayList和LinkedList所有面试问题

梦里梦外; 2022-05-09 07:40 330阅读 0赞

在面试中经常碰到:ArrayList和LinkedList的特点和区别?

这个问题的回答应该分成这几部分

  1. 介绍ArrayList底层实现
  2. 介绍LinkedList底层实现
  3. 两者个适用于哪些场合

  • ArrayList的源码解读

    public class ArrayList extends AbstractList

    1. implements List<E>, RandomAccess, Cloneable, java.io.Serializable

    {

    1. private static final long serialVersionUID = 8683452581122892189L;
    2. /**
    3. * Default initial capacity.
    4. */
    5. //默认容量是10
    6. private static final int DEFAULT_CAPACITY = 10;
    7. /**
    8. * Shared empty array instance used for empty instances.
    9. */
    10. //当传入ArrayList构造器的容量为0时用这个数组表示:容器的容量为0
    11. private static final Object[] EMPTY_ELEMENTDATA = {};
    12. /**
    13. * Shared empty array instance used for default sized empty instances. We
    14. * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
    15. * first element is added.
    16. */
    17. //主要作为一个标识位,在扩容时区分:默认大小和容量为0,使用默认容量时采取的是“懒加载”
    18. //即等到add元素的时候才进行实际容量的分配,后面扩容函数讲解还会提到这
    19. private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
    20. /**
    21. * The array buffer into which the elements of the ArrayList are stored.
    22. * The capacity of the ArrayList is the length of this array buffer. Any
    23. * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
    24. * will be expanded to DEFAULT_CAPACITY when the first element is added.
    25. */
    26. //ArrayList底层使用Object数组保存的元素的
    27. transient Object[] elementData; // non-private to simplify nested class access
    28. /**
    29. * The size of the ArrayList (the number of elements it contains).
    30. *
    31. * @serial
    32. */
    33. //记录当前容器中有多少元素
    34. private int size;
    35. //最常用的构造器之一,实际上就是创建了一个指定大小的Object数组来保存之后add的元素
    36. public ArrayList(int initialCapacity) {
    37. if (initialCapacity > 0) {
    38. this.elementData = new Object[initialCapacity];
    39. } else if (initialCapacity == 0) {
    40. this.elementData = EMPTY_ELEMENTDATA;
    41. } else {
    42. throw new IllegalArgumentException("Illegal Capacity: "+
    43. initialCapacity);
    44. }
    45. }

    //无参构造器,指向的是默认容量大小的Object数组,注意使用无参构造函数的时候并没有直接创建容量
    //为10的Object数组,而是采取懒加载的策略:使用DEFAULTCAPACITY_EMPTY_ELEMENTDATA(实际容量为0)
    //作为标识,在真正add元素时才会开辟Object数组,即在扩容函数中有处理默认容量的逻辑,后面会有分析

    1. public ArrayList() {
    2. this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    3. }

    //省略一部分不常用代码函数

  1. //add是ArrayList最常用的接口,逻辑很简单,
  2. public boolean add(E e) {
  3. //主要用于标识线程安全,即ArrayList只能在单线程环境下使用,在多线程环境下会出现并发安全问
  4. //题,modCount主要用于记录对ArrayList的修改次数,如果一个线程操作期间modCount发生了变化
  5. //即,有多个线程同时修改当前这个ArrayList,此时会抛出“ConcurrentModificationException”
  6. //异常,这又被称为“failFast机制”,在很多非线程安全的类中都有failFast机制:HashMap、
  7. //LinkedList等。这个机制主要用于迭代器、加强for循环等相关功能,也就是一个线程在迭代一个容器
  8. //时,如果其他线程改变了容器内的元素,迭代的这个线程会抛
  9. //出“ConcurrentModificationException”异常
  10. modCount++;
  11. //add操作的核心函数,当使用无参构造器时并没有直接分配大小为10的Object数组,这里面有对应
  12. //的处理逻辑
  13. add(e, elementData, size);
  14. return true;
  15. }
  16. private void add(E e, Object[] elementData, int s) {
  17. if (s == elementData.length)//如果使用无参构造器:开始时length为0,s也为0
  18. elementData = grow();//核心函数
  19. elementData[s] = e;
  20. size = s + 1;
  21. }
  22. private Object[] grow() {
  23. return grow(size + 1);//继续追踪
  24. }
  25. private Object[] grow(int minCapacity) {
  26. //使用数组复制的方式,扩容:将elementData所有元素复制到一个新数组中,这个新数组的长度是
  27. //newCapacity()函数的返回值,之后再把这个新数组赋值给elementData,完成扩容
  28. //进入newCapacity()函数
  29. return elementData = Arrays.copyOf(elementData,
  30. newCapacity(minCapacity));
  31. }
  32. private int newCapacity(int minCapacity) {//返回的是扩容后数组的长度
  33. // overflow-conscious code
  34. int oldCapacity = elementData.length;
  35. int newCapacity = oldCapacity + (oldCapacity >> 1);//扩容后为原来容量的1.5倍
  36. if (newCapacity - minCapacity <= 0) {
  37. if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA)//默认容量的处理
  38. return Math.max(DEFAULT_CAPACITY, minCapacity);
  39. //minCapacity是int类型,有溢出的可能,也就是ArrayList最大大小是Integer.MAX_VALUE
  40. if (minCapacity < 0) // overflow
  41. throw new OutOfMemoryError();
  42. return minCapacity;
  43. }
  44. //MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8,当扩容后大于MAX_ARRAY_SIZE ,返回
  45. //hugeCapacity(minCapacity),其实就是Integer.MAX_VALUE
  46. return (newCapacity - MAX_ARRAY_SIZE <= 0)
  47. ? newCapacity
  48. : hugeCapacity(minCapacity);
  49. }
  50. private static int hugeCapacity(int minCapacity) {
  51. if (minCapacity < 0) // overflow
  52. throw new OutOfMemoryError();
  53. return (minCapacity > MAX_ARRAY_SIZE)
  54. ? Integer.MAX_VALUE
  55. : MAX_ARRAY_SIZE;
  56. }
  57. //最后看下ArrayList的failFast机制
  58. private class Itr implements Iterator<E> {
  59. int cursor; // index of next element to return
  60. int lastRet = -1; // index of last element returned; -1 if no such
  61. //在迭代之前先保存modCount的值,modCount在改变容器元素、容器大小时会自增
  62. int expectedModCount = modCount;
  63. // prevent creating a synthetic constructor
  64. Itr() {}
  65. public boolean hasNext() {
  66. return cursor != size;
  67. }
  68. @SuppressWarnings("unchecked")
  69. public E next() {
  70. //使用迭代器遍历元素的时候先检查modCount的值是否等于预期的值,进入该函数
  71. checkForComodification();
  72. int i = cursor;
  73. if (i >= size)
  74. throw new NoSuchElementException();
  75. Object[] elementData = ArrayList.this.elementData;
  76. if (i >= elementData.length)
  77. throw new ConcurrentModificationException();
  78. cursor = i + 1;
  79. return (E) elementData[lastRet = i];
  80. }
  81. //可以发现:在迭代期间如果有线程改变了容器,此时会抛出“ConcurrentModificationException”
  82. final void checkForComodification() {
  83. if (modCount != expectedModCount)
  84. throw new ConcurrentModificationException();
  85. }
  86. ArrayList的其他操作:getremoveindexOf其实就很简单了,都是对Object数组的操作:获取数组某个索引位置的元素,删除数组中某个元素,查找数组中某个元素的位置......所以说理解原理很重要
  87. 上面注释的部分就是ArrayList的考点,主要有:初始容量、最大容量、使用Object数组保存元素(数组与链表的异同)、扩容机制(1.5倍)、failFast机制
  • LinkedList源码分析

    public class LinkedList

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

    {

    1. //LinkedList的size是int类型,但是后面会看到LinkedList大小实际只受内存大小的限制
    2. //也就是LinkedList的size大小可能发生溢出,返回负数
    3. transient int size = 0;
    4. /**
    5. * Pointer to first node.
    6. */
    7. //LinkedList底层使用双向链表实现,并保留了头尾两个节点的引用
    8. transient Node<E> first;//头节点
    9. /**
    10. * Pointer to last node.
    11. */
    12. transient Node<E> last;//尾节点
  1. //省略一部分无关代码,LinkedList内部类Node
  2. private static class Node<E> {
  3. E item;//元素值
  4. Node<E> next;//后继节点
  5. Node<E> prev;//前驱节点,即Node是双向链表
  6. Node(Node<E> prev, E element, Node<E> next) {//Node的构造器
  7. this.item = element;
  8. this.next = next;
  9. this.prev = prev;
  10. }
  11. }
  12. //LinkedList无参构造器:什么都没做
  13. public LinkedList() {}
  14. //LinkedList的大部分接口都是基于这几个接口实现的:
  15. //1.往链表头部插入元素
  16. //2.往链表尾部插入元素
  17. //3.在指定节点的前面插入一个节点
  18. //4.删除链表的头结点
  19. //5.删除除链表的尾节点
  20. //6.删除除链表中的指定节点
  21. private void linkFirst(E e) {//1.往链表头部插入元素
  22. final Node<E> f = first;
  23. final Node<E> newNode = new Node<>(null, e, f);
  24. first = newNode;
  25. if (f == null)
  26. last = newNode;
  27. else
  28. f.prev = newNode;
  29. size++;
  30. modCount++;//failFast机制
  31. }
  32. /**
  33. * Links e as last element.
  34. */
  35. void linkLast(E e) {//2.往链表尾部插入元素
  36. final Node<E> l = last;
  37. final Node<E> newNode = new Node<>(l, e, null);
  38. last = newNode;
  39. if (l == null)
  40. first = newNode;
  41. else
  42. l.next = newNode;
  43. size++;
  44. modCount++;//failFast机制
  45. }
  46. /**
  47. * Inserts element e before non-null Node succ.
  48. */
  49. void linkBefore(E e, Node<E> succ) {//3.在指定节点(succ)的前面插入一个节点
  50. // assert succ != null;
  51. final Node<E> pred = succ.prev;
  52. final Node<E> newNode = new Node<>(pred, e, succ);
  53. succ.prev = newNode;
  54. if (pred == null)
  55. first = newNode;
  56. else
  57. pred.next = newNode;
  58. size++;
  59. modCount++;//failFast机制
  60. }
  61. /**
  62. * Unlinks non-null first node f.
  63. */
  64. private E unlinkFirst(Node<E> f) {//4.删除链表的头结点
  65. // assert f == first && f != null;
  66. final E element = f.item;
  67. final Node<E> next = f.next;
  68. f.item = null;
  69. f.next = null; // help GC
  70. first = next;
  71. if (next == null)
  72. last = null;
  73. else
  74. next.prev = null;
  75. size--;
  76. modCount++;//failFast机制
  77. return element;
  78. }
  79. /**
  80. * Unlinks non-null last node l.
  81. */
  82. private E unlinkLast(Node<E> l) {//5.删除除链表的尾节点
  83. // assert l == last && l != null;
  84. final E element = l.item;
  85. final Node<E> prev = l.prev;
  86. l.item = null;
  87. l.prev = null; // help GC
  88. last = prev;
  89. if (prev == null)
  90. first = null;
  91. else
  92. prev.next = null;
  93. size--;
  94. modCount++;//failFast机制
  95. return element;
  96. }
  97. /**
  98. * Unlinks non-null node x.
  99. */
  100. E unlink(Node<E> x) {//6.删除除链表中的指定节点
  101. // assert x != null;
  102. final E element = x.item;
  103. final Node<E> next = x.next;
  104. final Node<E> prev = x.prev;
  105. if (prev == null) {
  106. first = next;
  107. } else {
  108. prev.next = next;
  109. x.prev = null;
  110. }
  111. if (next == null) {
  112. last = prev;
  113. } else {
  114. next.prev = prev;
  115. x.next = null;
  116. }
  117. x.item = null;
  118. size--;
  119. modCount++;//failFast机制
  120. return element;
  121. }
  122. //LinkedList常用接口的实现
  123. public E removeFirst() {
  124. final Node<E> f = first;
  125. if (f == null)
  126. throw new NoSuchElementException();
  127. return unlinkFirst(f);//调用 4.删除链表的头结点 实现
  128. }
  129. public E removeLast() {
  130. final Node<E> l = last;
  131. if (l == null)
  132. throw new NoSuchElementException();
  133. return unlinkLast(l);//调用 5.删除除链表的尾节点 实现
  134. }
  135. public void addFirst(E e) {
  136. linkFirst(e);//调用 1.往链表头部插入元素 实现
  137. }
  138. public void addLast(E e) {
  139. linkLast(e);//调用 2.往链表尾部插入元素 实现
  140. }
  141. public boolean add(E e) {
  142. linkLast(e);//调用 2.往链表尾部插入元素 实现
  143. return true;
  144. }
  145. public boolean remove(Object o) {
  146. if (o == null) {
  147. for (Node<E> x = first; x != null; x = x.next) {
  148. if (x.item == null) {
  149. unlink(x);//调用 6.删除除链表中的指定节点 实现
  150. return true;
  151. }
  152. }
  153. } else {
  154. for (Node<E> x = first; x != null; x = x.next) {
  155. if (o.equals(x.item)) {
  156. unlink(x);//调用 6.删除除链表中的指定节点 实现
  157. return true;
  158. }
  159. }
  160. }
  161. return false;
  162. }
  163. //省略其他无关函数
  164. //迭代器中的failFast机制
  165. private class ListItr implements ListIterator<E> {
  166. private Node<E> lastReturned;
  167. private Node<E> next;
  168. private int nextIndex;
  169. //在迭代之前先保存modCount的值,modCount在改变容器元素、容器大小时会自增
  170. private int expectedModCount = modCount;
  171. ListItr(int index) {
  172. // assert isPositionIndex(index);
  173. next = (index == size) ? null : node(index);
  174. nextIndex = index;
  175. }
  176. public boolean hasNext() {
  177. return nextIndex < size;
  178. }
  179. public E next() {
  180. 使用迭代器遍历元素的时候先检查modCount的值是否等于预期的值,进入该函数
  181. checkForComodification();
  182. if (!hasNext())
  183. throw new NoSuchElementException();
  184. lastReturned = next;
  185. next = next.next;
  186. nextIndex++;
  187. return lastReturned.item;
  188. }
  189. //可以发现:在迭代期间如果有线程改变了容器,此时会抛出“ConcurrentModificationException”
  190. final void checkForComodification() {
  191. if (modCount != expectedModCount)
  192. throw new ConcurrentModificationException();
  193. }
  194. LinkedList的实现较为简单:底层使用双向链表实现、保留了头尾两个指针、LinkedList的其他操作基本都是基于上面那7个函数实现的,另外LinkedList也有FailFast机制:这个机制主要在迭代器中会使用。
  • 数组和链表各自的特性

数组和链表的特性差异,本质是:连续空间存储和非连续空间存储的差异,主要有下面两点:

  1. ArrayList:底层是Object数组实现的:由于数组的地址是连续的,数组支持O(1)随机访问;数组在初始化时需要指定容量;数组不支持动态扩容,像ArrayList、Vector和Stack使用的时候看似不用考虑容量问题(因为可以一直往里面存放数据);但是它们的底层实际做了扩容;数组扩容代价比较大,需要开辟一个新数组将数据拷贝进去,数组扩容效率低;适合读数据较多的场合
  2. LinkedList:底层使用一个Node数据结构,有前后两个指针,双向链表实现的。相对数组,链表插入效率较高,只需要更改前后两个指针即可;另外链表不存在扩容问题,因为链表不要求存储空间连续,每次插入数据都只是改变last指针;另外,链表所需要的内存比数组要多,因为他要维护前后两个指针;它适合删除,插入较多的场景。另外,LinkedList还实现了Deque接口。

扫描下方二维码,及时获取更多互联网求职面经javapython爬虫大数据等技术,和海量资料分享
公众号菜鸟名企梦后台发送“csdn”即可免费领取【csdn】和【百度文库】下载服务;
公众号菜鸟名企梦后台发送“资料”:即可领取5T精品学习资料java面试考点java面经总结,以及几十个java、大数据项目资料很全,你想找的几乎都有

扫码关注,及时获取更多精彩内容。(博主今日头条大数据工程师)

扫码关注,及时获取更多精彩内容。(博主今日头条大数据工程师)

发表评论

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

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

相关阅读