List之ArrayList源码实现

雨点打透心脏的1/2处 2022-05-14 01:05 243阅读 0赞

一、引言

1.导语

  • 集合是Java重要且非常基础的东西,因为任何数据必不可少的就是该数据是如何存储的,集合的作用就是以一定的方式组织、存储数据。所以说研究其底层源代码是一个程序员的必修课。

2.要点


























要点 说明
是否可以为空
是否有序
是否可以重复
是否线程安全

只要在学习集合源码的时候的时刻牢记这四点,就会时刻思路比较清晰,更便于我们去理解其设计思想和实现。

二、分析

1. 继承关系图

这里写图片描述

2. 字段

  1. ```
  2. /**
  3. * Default initial capacity. 初始化容量大小为10
  4. */
  5. private static final int DEFAULT_CAPACITY = 10;
  6. /**
  7. * Shared empty array instance used for empty instances.
  8. * 空的数组
  9. */
  10. private static final Object[] EMPTY_ELEMENTDATA = {};
  11. /**
  12. * Shared empty array instance used for default sized empty instances. We
  13. * distinguish this from EMPTY_ELEMENTDATA to know how much to inflate when
  14. * first element is added.
  15. */
  16. private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};
  17. // 当前数据对象存放地方,当前对象不参与序列化
  18. transient Object[] elementData; // non-private to simplify nested class access
  19. /**
  20. * The size of the ArrayList (the number of elements it contains).
  21. * 数组中的元素个数
  22. */
  23. private int size;
  24. ```

3. 构造函数

3.1 空参构造函数

  1. ```
  2. public ArrayList() {
  3. this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
  4. }
  5. ```
  6. >注意:此时ArrayListsize为空,但是elementDatalength1。第一次添加时,容量变成初始容量大小10.

3.2 int参数构造函数

  1. ```
  2. public ArrayList(int initialCapacity) {
  3. if (initialCapacity > 0) {
  4. this.elementData = new Object[initialCapacity];
  5. } else if (initialCapacity == 0) {
  6. this.elementData = EMPTY_ELEMENTDATA;
  7. } else {
  8. throw new IllegalArgumentException("Illegal Capacity: "+
  9. initialCapacity);
  10. }
  11. }
  12. ```
  13. > 注意:此时ArrayListsize为空,但是elementDatalength1。第一次添加时,容量变成初始容量大小10.

3.3 collection参数构造函数

  1. public ArrayList(Collection<? extends E> c) {
  2. // 指定 collection 的元素的列表,这些元素是按照该 collection 的迭代器返回它们的顺序排
  3. // 这里主要做了两步:1.把集合的元素copy到elementData中。2.更新size值。
  4. elementData = c.toArray();
  5. if ((size = elementData.length) != 0) {
  6. // c.toArray might (incorrectly) not return Object[] (see 6260652)
  7. if (elementData.getClass() != Object[].class)
  8. elementData = Arrays.copyOf(elementData, size, Object[].class);
  9. } else {
  10. // replace with empty array.
  11. this.elementData = EMPTY_ELEMENTDATA;
  12. }
  13. }

4. add方法

  1. /** * Appends the specified element to the end of this list. * * @param e element to be appended to this list * @return <tt>true</tt> (as specified by {@link Collection#add}) */
  2. public boolean add(E e) {
  3. // 扩容操作,稍后讲解
  4. ensureCapacityInternal(size + 1); // Increments modCount!!
  5. // 将元素添加到数组尾部
  6. elementData[size++] = e;
  7. return true;
  8. }

5.ensureCapacityInternal方法

  1. /** * Increases the capacity of this <tt>ArrayList</tt> instance, if 增加arrayList的容量 * necessary, to ensure that it can hold at least the number of elements * specified by the minimum capacity argument. 确保他能装下最新插入的元素 * * @param minCapacity the desired minimum capacity */
  2. public void ensureCapacity(int minCapacity) {
  3. // 如果elementData为DEFAULTCAPACITY_EMPTY_ELEMENTDATA,则扩容容量为默认值(10),否则就为0
  4. int minExpand = (elementData != DEFAULTCAPACITY_EMPTY_ELEMENTDATA)
  5. // any size if not default element table
  6. ? 0
  7. // larger than default for default empty table. It's already
  8. // supposed to be at default size.
  9. : DEFAULT_CAPACITY;
  10. if (minCapacity > minExpand) {
  11. ensureExplicitCapacity(minCapacity);
  12. }
  13. }
  14. // 数组容量检测,不够时则进行扩容操作
  15. private void ensureCapacityInternal(int minCapacity) {
  16. // 如果elementData为默认的空数组,则容量扩容为默认容量和参数容量的较大值
  17. if (elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
  18. minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
  19. }
  20. // 进行扩容操作
  21. ensureExplicitCapacity(minCapacity);
  22. }
  23. private void ensureExplicitCapacity(int minCapacity) {
  24. modCount++;
  25. // overflow-conscious code
  26. // 如果当前指定的最小容量比缓冲区的长度大,则进行扩容,并且扩容的长度为指定的minCapacityd;
  27. // 否则不进行扩容
  28. if (minCapacity - elementData.length > 0)
  29. grow(minCapacity);
  30. }
  31. /** * The maximum size of array to allocate. * Some VMs reserve some header words in an array. * Attempts to allocate larger arrays may result in * OutOfMemoryError: Requested array size exceeds VM limit * 具体最大为什么是Integer.MAX_VALUE - 8,这上面的英文说的很清楚。 * 大概的意思:jvm中有一些头元素会存在数组中,所以预留了8个空的,防止oom. */
  32. private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; // 数组的最大值:Integer的最大值-8
  33. /** * Increases the capacity to ensure that it can hold at least the * number of elements specified by the minimum capacity argument. * * @param minCapacity the desired minimum capacity */
  34. private void grow(int minCapacity) {
  35. // overflow-conscious code
  36. int oldCapacity = elementData.length;
  37. // 新容量 = 原来容量 + (原来容量)/2
  38. int newCapacity = oldCapacity + (oldCapacity >> 1);
  39. // 如果新容量比指定的容量小,则把新容量赋值为新容量。
  40. if (newCapacity - minCapacity < 0)
  41. newCapacity = minCapacity;
  42. // 如果新容量比最大的数组大,则进行大容量扩容
  43. if (newCapacity - MAX_ARRAY_SIZE > 0)
  44. newCapacity = hugeCapacity(minCapacity);
  45. // minCapacity is usually close to size, so this is a win:
  46. // 创建新容量长度的数组,并把原来的元素赋值到新数组中,实现扩容 + 复制 元素的效果
  47. elementData = Arrays.copyOf(elementData, newCapacity);
  48. }
  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. }

思考:
1.判断是否需要扩容,如果需要,计算需要扩容的最小容量
2.如果确定扩容,就执行grow(int minCapacity),minCapacity为最少需要的容量
3.第一次扩容是的容量大小是原来的1.5倍
4如果第一次 扩容后容量还是小于minCapacity,那就扩容为minCapacity
5.最后,如果minCapacity大于最大容量,则就扩容为最大容量

6.get(int)方法

  1. public E get(int index) {
  2. // 先进行越界检查
  3. rangeCheck(index);
  4. // 通过检查则返回结果数据,否则就抛出异常。
  5. return elementData(index);
  6. }
  7. // 越界检查的代码很简单,就是判断想要的索引有没有超过当前数组的最大容量
  8. private void rangeCheck(int index) {
  9. if (index >= size)
  10. throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  11. }

7.add(int, E)方法

  1. public void add(int index, E element) {
  2. // 插入数组位置检查
  3. rangeCheckForAdd(index);
  4. // 确保容量,如果需要扩容的话则自动扩容
  5. ensureCapacityInternal(size + 1); // Increments modCount!!
  6. System.arraycopy(elementData, index, elementData, index + 1,
  7. size - index); // 将index后面的元素往后移一个位置
  8. elementData[index] = element; // 在想要插入的位置插入元素
  9. size++; // 元素大小加1
  10. }
  11. // 针对插入数组的位置,进行越界检查,不通过抛出异常
  12. // 必须在0-最后一个元素中间的位置插入,,否则就报错
  13. // 因为数组是连续的空间,不存在断开的情况
  14. private void rangeCheckForAdd(int index) {
  15. if (index > size || index < 0)
  16. throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  17. }
  • 对将index后面的元素往后移一个位置的图形说明,更容易理解(网上随便找了一个,侵删)。
    这里写图片描述

8.remove(int index)

  1. public E remove(int index) {
  2. // 索引越界检查
  3. rangeCheck(index);
  4. modCount++;
  5. // 得到删除位置元素值
  6. E oldValue = elementData(index);
  7. // 计算删除元素后,元素右边需要向左移动的元素个数
  8. int numMoved = size - index - 1;
  9. if (numMoved > 0)
  10. // 进行移动操作,图形过程大致类似于上面的add(int, E)
  11. System.arraycopy(elementData, index+1, elementData, index,
  12. numMoved);
  13. // 元素大小减1,并且将最后一个置为null.
  14. // 置为null的原因,就是让gc起作用,所以需要显示置为null
  15. elementData[--size] = null; // clear to let GC do its work
  16. // 返回删除的元素值
  17. return oldValue;
  18. }

9.remove(Object o)

  1. public boolean remove(Object o) {
  2. // 如果删除元素为null,则循环找到第一个null,并进行删除
  3. if (o == null) {
  4. for (int index = 0; index < size; index++)
  5. if (elementData[index] == null) {
  6. // 根据下标删除
  7. fastRemove(index);
  8. return true;
  9. }
  10. } else {
  11. // 否则就找到数组中和o相等的元素,返回下标进行删除
  12. for (int index = 0; index < size; index++)
  13. if (o.equals(elementData[index])) {
  14. // 根据下标删除
  15. fastRemove(index);
  16. return true;
  17. }
  18. }
  19. return false;
  20. }
  21. private void fastRemove(int index) {
  22. modCount++;
  23. // 计算删除元素后,元素右边需要向左移动的元素个数
  24. int numMoved = size - index - 1;
  25. if (numMoved > 0)
  26. // 进行移动操作
  27. System.arraycopy(elementData, index+1, elementData, index,
  28. numMoved);
  29. // 元素大小减1,并且将最后一个置为null. 原因同上。
  30. elementData[--size] = null; // clear to let GC do its work
  31. }

10.set(int index, E element)

  1. // 这个很简单,看下代码基本上都能理解
  2. // 作用:替换指定索引的元素
  3. public E set(int index, E element) {
  4. // 索引越界检查
  5. rangeCheck(index);
  6. E oldValue = elementData(index);
  7. elementData[index] = element;
  8. return oldValue;
  9. }

三、结尾

1.ArrayList的优缺点


























要点 说明
优点1 ArrayList底层以数组实现,是一种随机访问模式,再加上它实现了RandomAccess接口,因此查找也就是get的时候非常快
优点2 ArrayList在顺序添加一个元素的时候非常方便,只是往数组里面添加了一个元素而已
缺点1 删除元素时,涉及到元素复制,如果要复制的元素很多,那么就会比较耗费性能
缺点2 插入元素时,涉及到元素复制,如果要复制的元素很多,那么就会比较耗费性能

ArrayList比较适合顺序添加、随机访问的场景

2.ArrayList和Vector的不同

  • ArrayList是线程非安全的,Vector则是线程安全的。Vector中90%的方法和ArrayList的是一样的。
  • Vector可以指定增长因子,而ArrayList不行,而且两者默认扩容的大小也是不一样的,一个1.5倍;一个是2倍而且还可以指定。
  • 针对第一点中的缺点,jdk也给出了解决方法:

    List synchronizedList = Collections.synchronizedList(list);
    // 此时list则是一个线程安全的集合

3.为什么ArrayList的elementData是用transient修饰的

  • 说明:ArrayList实现了Serializable接口,这意味着ArrayList是可以被序列化的,用transient修饰elementData意味着我不希望elementData数组被序列化
  • 理解:序列化ArrayList的时候,ArrayList里面的elementData未必是满的,比方说elementData有10的大小,但是我只用了其中的3个,那么是否有必要序列化整个elementData呢?显然没有这个必要,因此ArrayList中重写了writeObject方法。

    private void writeObject(java.io.ObjectOutputStream s)

    1. throws java.io.IOException{
    2. // Write out element count, and any hidden stuff
    3. int expectedModCount = modCount;
    4. s.defaultWriteObject();
    5. // Write out size as capacity for behavioural compatibility with clone()
    6. s.writeInt(size);
    7. // Write out all elements in the proper order.
    8. for (int i=0; i<size; i++) {
    9. s.writeObject(elementData[i]);
    10. }
    11. if (modCount != expectedModCount) {
    12. throw new ConcurrentModificationException();
    13. }
    14. }
  • 优点:这样做既提高了序列化的效率,减少了无意义的序列化;而且还减少了序列化后文件大小。

4.版本说明

  • 这里的源码是JDK8版本,不同版本可能会有所差异,但是基本原理都是一样的。

5.回顾和思考

  • 再次思考学习集合源码的四个目标和上面的具体的内容,是不是有一种恍然大悟的感觉!!!

发表评论

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

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

相关阅读

    相关 ListLinkedList实现

    一、引言 1.概念 LinkedList是基于链表实现的,所以先讲解一下什么是链表。链表原先是C/C++的概念,是一种线性的存储结构,意思是将要存储的数据存在