Java集合框架概览之ArrayList源码分析

其他教程   发布日期:2024年04月19日   浏览次数:312

今天小编给大家分享一下Java集合框架概览之ArrayList源码分析的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。

一、从一段简单的代码入手

下面是一段简单的集合操作代码,实例化一个 ArrayList 集合并插入和获取元素的代码:

  1. public static void main(String[] args) {
  2. // 实例化一个初始容量为5的 ArrayList 集合
  3. List list = new ArrayList<String>(6);
  4. // 向指定索引位置插入数据
  5. list.add(1, "hello");// 代码行号:17
  6. // 获取指定索引位置的数据
  7. System.out.println(list.get(1));
  8. }

小伙伴可以先思考一下执行的结果是什么?

好啦,揭晓谜底:

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 0
at java.util.ArrayList.rangeCheckForAdd(ArrayList.java:665)
at java.util.ArrayList.add(ArrayList.java:477)
at com.example.qgdemo.studydemo.Test.Test2.main(Test2.java:17)

细心的小伙伴已经注意到了上面的那段代码有一行专门标注了行号,而执行的结果的异常行号刚好是我标注的那一行,不难得出 就是在:

  1. list.add(1, "hello");
这一行就抛出了异常。那么问题到底出现在哪里了呢?

下面我们从这短短几行代码逐行深入源码去刨析,挖出隐藏宝藏。

二、初始化

ArrayList的初始化

先从集合的初始化入手:

  1. List list = new ArrayList<String>(5);

上源码(硬菜):

  1. /**
  2. * The array buffer into which the elements of the ArrayList are stored.
  3. * The capacity of the ArrayList is the length of this array buffer. Any
  4. * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
  5. * will be expanded to DEFAULT_CAPACITY when the first element is added.
  6. */
  7. transient Object[] elementData; // non-private to simplify nested class access
  8. /**
  9. * Shared empty array instance used for empty instances.
  10. */
  11. private static final Object[] EMPTY_ELEMENTDATA = {};
  12. /**
  13. * Constructs an empty list with the specified initial capacity.
  14. * 根据指定的初始化容量构造一个空的 list 集合
  15. * @param initialCapacity the initial capacity of the list 初始化的容量
  16. * @throws IllegalArgumentException if the specified initial capacity
  17. * is negative 如果指定的容量为负数则抛出异常
  18. */
  19. public ArrayList(int initialCapacity) {
  20. if (initialCapacity > 0) {
  21. this.elementData = new Object[initialCapacity];
  22. } else if (initialCapacity == 0) {
  23. this.elementData = EMPTY_ELEMENTDATA;
  24. } else {
  25. throw new IllegalArgumentException("Illegal Capacity: "+
  26. initialCapacity);
  27. }
  28. }

简单分析一下这段源码:

  • ArrayList 底层采用普通的数组来存储数据,通过

    1. elementData
    这一成员变量来存储集合的数据。
  • 在实例化是当传入的参数大于零,则实例化一个对应容量的 Object 数组并赋值给我们的

    1. elementData
    成员变量。
  • 在实例化是当传入的参数等于零,安装默认的

    1. EMPTY_ELEMENTDATA
    空数组赋值给elementData 成员变量。
  • 在实例化是当传入的参数小于零,则抛出指定的 IllegalArgumentException 异常信息。

小贴士: 细心的小伙伴会注意到我们的

  1. elementData
成员变量使用了
  1. transient
关键字修饰,这里简单科普一下:

被 transient 修饰的变量不能被序列化。

transient 只能作用于实现了 Serializable 接口的类当中。

transient 只能用来修饰普通成员变量字段。

分析到这里目前没有发现关于我们的问题的信息,我们继续往下看。

三、添加元素

ArrayList添加元素

现在到了我们的重头戏,从执行结果反馈来看,抛出异常的位置就在这:

  1. list.add(1, "hello");
,让我们磨刀霍霍向源码一探究竟。
  1. /**
  2. * Inserts the specified element at the specified position in this
  3. * list. Shifts the element currently at that position (if any) and
  4. * any subsequent elements to the right (adds one to their indices).
  5. * 向 ArrayList 中指定的位置插入指定的元素,如果当前位置已经有元素,则会将该位置之后的所有元素统一往后移一位。
  6. * @param index index at which the specified element is to be inserted 待插入的索引位置
  7. * @param element element to be inserted 待插入的元素
  8. * @throws IndexOutOfBoundsException {@inheritDoc} 下标越界异常
  9. */
  10. public void add(int index, E element) {
  11. rangeCheckForAdd(index); // 越界检查
  12. ensureCapacityInternal(size + 1); // Increments modCount!! 是否扩容的判断
  13. System.arraycopy(elementData, index, elementData, index + 1,
  14. size - index); // 数组拷贝
  15. elementData[index] = element; // 将待添加的元素放入指定的位置
  16. size++; // 集合的实际大小累加
  17. }
  18. /**
  19. * The size of the ArrayList (the number of elements it contains).
  20. * ArrayList 的成员变量,保存了已有元素的数量
  21. * @serial
  22. */
  23. private int size;
  24. /**
  25. * A version of rangeCheck used by add and addAll.
  26. */
  27. private void rangeCheckForAdd(int index) {
  28. if (index > size || index < 0)
  29. throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  30. }

源码刨析:

  • 首先看

    1. rangeCheckForAdd(index);
    这一行,这个方法主要是检查待插入的 index 索引是否越界或者非法。 经过缜密分析(debug ),发现正是这里的检查抛出的异常,导致我们出师未捷身先死/(ㄒoㄒ)/~~,第一步就被绊倒了。
  • 既然判断的是 index 和 size 的大小,那么我们回过头看一下:

    1. private int size;
    这个玩意,通过其注释我们得知这个成员变量保存了已有元素的数量,那么问题就很明显了:我们初始化后的集合虽然已经有了一个指定容量的数组,但是并没有实际元素,所以 size 依然为0。不难得出结论:==这种指定位置插入元素的方法必须从下标0开始顺次插入元素,你敢隔空插入它就敢死给你看!==

好了,虽然问题的根源找到了,但是源码我们还是要继续往下看的。

  1. // 判断是否需要扩容
  2. private void ensureCapacityInternal(int minCapacity) {
  3. ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
  4. }
  5. private void ensureExplicitCapacity(int minCapacity) {
  6. modCount++; // 修改次数累加
  7. // overflow-conscious code
  8. if (minCapacity - elementData.length > 0)
  9. grow(minCapacity);
  10. }
  11. /**
  12. * Increases the capacity to ensure that it can hold at least the
  13. * number of elements specified by the minimum capacity argument.
  14. * 增加集合的容量以确保容纳至少
  15. * @param minCapacity the desired minimum capacity
  16. */
  17. private void grow(int minCapacity) {
  18. // overflow-conscious code
  19. int oldCapacity = elementData.length;
  20. int newCapacity = oldCapacity + (oldCapacity >> 1);// 将原容量扩容至原来的1.5倍,以本例来说就是扩容至:6+3=9
  21. if (newCapacity - minCapacity < 0)
  22. newCapacity = minCapacity; //取 newCapacity 和 minCapacity 的最大值赋值给 newCapacity,考虑了溢出的情况
  23. if (newCapacity - MAX_ARRAY_SIZE > 0)
  24. newCapacity = hugeCapacity(minCapacity);
  25. // minCapacity is usually close to size, so this is a win:
  26. elementData = Arrays.copyOf(elementData, newCapacity);
  27. }
  28. /**
  29. * The maximum size of array to allocate. 定义了数组允许分配的最大长度
  30. * Some VMs reserve some header words in an array. 一些虚拟机在数列中会保留一些头部信息(需要预留一定容量)
  31. * Attempts to allocate larger arrays may result in 尝试取分配更长的数组可能会导致内存溢出
  32. * OutOfMemoryError: Requested array size exceeds VM limit :申请的数组长度超过了虚拟机的限制
  33. */
  34. private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
  35. private static int hugeCapacity(int minCapacity) {
  36. if (minCapacity < 0) // overflow 溢出检查
  37. throw new OutOfMemoryError();
  38. return (minCapacity > MAX_ARRAY_SIZE) ? // 如果申请的最小容量比数组的容量上限还大则容量设置为:
  39. Integer.MAX_VALUE : // Integer.MAX_VALUE,否则设置为:数组容量上限(MAX_ARRAY_SIZE)
  40. MAX_ARRAY_SIZE;
  41. }

源码刨析:

  • 这一方法:

    1. private void ensureCapacityInternal(int minCapacity)
    主要是为了检查集合是否可以满足指定的最小数量的元素的要求。
  • 如果满足的话,则只需要将修改次数:

    1. modCount++
    累加就完事。
  • 如果容量不够用了,则需要进行扩容,那么就需要调用

    1. grow(int minCapacity)
    方法来执行扩容任务。
  • 通过

    1. int newCapacity = oldCapacity + (oldCapacity >> 1);
    方法将原来的容量扩容1.5倍,后续的两个 if 判断考虑了 newCapacity 溢出的情况,最终保证了 newCapacity 必然为正数。

小贴士: 上面的:

  1. grow(int minCapacity)
方法用到了移位运算符。 java中有三种移位运算符:
  1. <<
:左移运算符,num << 1,相当于num乘以2。
  1. >>
:右移运算符,num >> 1,相当于num除以2。
  1. >>>
:无符号右移,忽略符号位,空位都以0补齐。

确定了集合的新容量,接下来就需要将集合的旧数据拷贝到新数组当中:

  1. System.arraycopy(elementData, index, elementData, index + 1,
  2. size - index);
  3. //[#System] 调用了系统级的数组拷贝方法
  4. /**
  5. * @param src the source array. 源数组
  6. * @param srcPos starting position in the source array. 源数组的起始下标
  7. * @param dest the destination array. 目标数组
  8. * @param destPos starting position in the destination data. 目标数组的起始下标
  9. * @param length the number of array elements to be copied. 需要拷贝的元素数量
  10. * */
  11. public static native void arraycopy(Object src, int srcPos,
  12. Object dest, int destPos,
  13. int length);

源码刨析:

  • 这块内容没啥好说的,无非就是调用系统函数进行新旧数据的拷贝。

  • 主要看看上面数组拷贝方法的注释,做一个大致的了解。

四、ArrayList获取元素

ArrayList 由于是基于数组来存储数据的,所以支持按指定下标来获取数据:

  1. /**
  2. * Returns the element at the specified position in this list.
  3. * 返回集合指定位置的元素
  4. * @param index index of the element to return 要返回的元素下标
  5. * @return the element at the specified position in this list 指定下标的元素
  6. * @throws IndexOutOfBoundsException {@inheritDoc} 下标越界异常
  7. */
  8. public E get(int index) {
  9. rangeCheck(index); // 索引越界检查
  10. return elementData(index); // 按下标获取元素
  11. }
  12. /**
  13. * Checks if the given index is in range. If not, throws an appropriate
  14. * runtime exception. This method does *not* check if the index is
  15. * negative: It is always used immediately prior to an array access,
  16. * which throws an ArrayIndexOutOfBoundsException if index is negative.
  17. */
  18. private void rangeCheck(int index) {
  19. if (index >= size)
  20. throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  21. }

源码刨析:

  • 这块内容主要也就进行了一次下标越界的检查,检查通过就直接返回数据。

五、删除元素

ArrayList 主要提供了:指定下标删除,按元素删除,批量删除,特定条件删除,下标区间删除等方法。

5.1 指定下标删除

  1. /**
  2. * Removes the element at the specified position in this list.
  3. * Shifts any subsequent elements to the left (subtracts one from their
  4. * indices).
  5. * 删除特定位置的集合元素,将该元素之后的所有元素往前挪一位。
  6. * @param index the index of the element to be removed 待删除的元素下标
  7. * @return the element that was removed from the list 返回已删除的元素
  8. * @throws IndexOutOfBoundsException {@inheritDoc} 下标越界异常
  9. */
  10. public E remove(int index) {
  11. rangeCheck(index); // 下标越界检查
  12. modCount++; // 修改次数累加
  13. E oldValue = elementData(index);
  14. int numMoved = size - index - 1; // 计算需要移动的元素数量,指的就是当前删除位置之后的元素数量
  15. if (numMoved > 0)
  16. System.arraycopy(elementData, index+1, elementData, index,
  17. numMoved); // 重新进行数据拷贝
  18. elementData[--size] = null; // clear to let GC do its work 将数组末尾空缺出来的位置引用置为null,便于GC
  19. return oldValue;
  20. }

源码刨析:

  • 首先就是进行下标越界的检查,然后就是修改次数的累加以及获取待删除的旧数据。

  • 这块:

    1. int numMoved = size - index - 1;
    主要是计算一下当前待删除元素之后有多少需要移动的元素数量。
  • 这个

    1. numMoved
    的值可能为 0 ,比如说当前集合就一个元素,在删除下标为 0 的时候,
    1. numMoved
    的值就为 0 ,所以接下来做了一次 if 是否大于零的判断,如果为 true,则执行数组的拷贝,将需要处理的元素全部往前移动一位。
  • 上一步移动完元素之后,数组的最后一个位置就空缺出来了,然后就通过

    1. elementData[--size] = null;
    将该位置的引用置为 null 便于GC处理。

5.2 按元素删除

  1. /**
  2. * Removes the first occurrence of the specified element from this list,
  3. * 如果集合中指定的元素存在的话,删除首次出现的那个指定元素。
  4. * if it is present. If the list does not contain the element, it is
  5. * 如果指定元素不存在,则不会有什么影响。
  6. * unchanged. More formally, removes the element with the lowest index
  7. * <tt>i</tt> such that
  8. * 一般情况下,会删除下标最小的那个元素
  9. * <tt>(o==null ? get(i)==null : o.equals(get(i)))</tt>
  10. * (if such an element exists). Returns <tt>true</tt> if this list
  11. * contained the specified element (or equivalently, if this list
  12. * changed as a result of the call).
  13. *
  14. * @param o element to be removed from this list, if present 待删除的元素
  15. * @return <tt>true</tt> if this list contained the specified element 如果元素存在则返回true,反之为false
  16. */
  17. public boolean remove(Object o) {
  18. if (o == null) { // 如果待删除的元素为 null,则直接遍历数组元素和 null 进行匹配
  19. for (int index = 0; index < size; index++)
  20. if (elementData[index] == null) {
  21. fastRemove(index); // 执行删除操作
  22. return true;
  23. }
  24. } else {
  25. for (int index = 0; index < size; index++)
  26. if (o.equals(elementData[index])) { // 遍历匹配所有元素
  27. fastRemove(index);// 执行删除操作
  28. return true;
  29. }
  30. }
  31. return false;
  32. }
  33. /*
  34. * Private remove method that skips bounds checking and does not
  35. * return the value removed.
  36. */
  37. private void fastRemove(int index) {
  38. modCount++; // 修改次数累加
  39. int numMoved = size - index - 1;// 计算需要移动的元素数量,指的就是当前删除位置之后的元素数量
  40. if (numMoved > 0)
  41. System.arraycopy(elementData, index+1, elementData, index,
  42. numMoved);// 重新进行数据拷贝
  43. elementData[--size] = null; // clear to let GC do its work 将数组末尾空缺出来的位置引用置为null,便于GC
  44. }

源码刨析:

  • 首先根据待删除的元素是否为

    1. null
    进行分别处理。
  • 如果待删除的元素是

    1. null
    的话,则遍历所有数组元素和
    1. null
    进行匹配,匹配到第一个的话则执行删除,直接返回true。
  • 如果不是,则遍历所有数组元素和待删除元素进行

    1. equals
    匹配,匹配到第一个的话则执行删除,直接返回true。
  • 对于

    1. fastRemove
    这个方法的话,笔者认为在上一个指定下标删除的时候可以直接调用这个方法的。

小贴士: 由上述源码可以得出一个结论:==如果你想删除一个

  1. ArrayList
中的 所有
  1. null
元素,调用一次
  1. remove(null);
是无法删除全部的null元素的。==

5.3 批量删除

  1. /**
  2. * Removes from this list all of its elements that are contained in the
  3. * specified collection.
  4. * 按给定的特定元素集合去删除当前集合的匹配元素。
  5. * @param c collection containing elements to be removed from this list 包含待删除元素的删除
  6. * @return {@code true} if this list changed as a result of the call
  7. * @throws ClassCastException if the class of an element of this list
  8. * is incompatible with the specified collection
  9. * (<a href="https://www.19jp.com">

源码刨析:

  • 首先对传入的参数集合进行

    1. null
    判断,如果为空则直接抛出异常。
  • 接下来就是通过

    1. batchRemove
    方法执行批量删除。
  • 这个:

    1. batchRemove
    方法首先会遍历原集合,使用其 [r] 位置元素去匹配在待删除集合是否存在:
  • 如果不存在,说明该元素并不是要删除元素,则:

    1. if (c.contains(elementData[r]) == complement)
    返回true,此时的原集合的 [r] 位置元素需要覆盖到原集合的 [w] 位置,此时 [w] 进行累加,方便下次进行覆盖。
  • 在循环完毕后,最终的结果就是:原集合的 [w] 位置之前的元素都是需要保留下来的。

    1. finally
    代码块中:进行的第一个
    1. if (r != size)
    判断是为了在出现异常时(
    1. 此时r != size
    )单独将后续未处理完的 [r] 之后数据拷贝到原集合的 [r] 之后,保证数据的完整性。另外还需要重新计算 [w] 的值。
  • 在这一步:

    1. if (w != size)
    判断是为了将 [w] 之后的重叠需要删除的数据赋值为 null,最后修改 modCount 和集合的大小 size 的值。
  • 总之按博主的理解,这个

    1. batchRemove
    方法总体思想是:将原数组中不匹配的元素通过替换的方式往前聚集,处理到最后那么后面的那部分元素就可以废弃掉了。

5.4 特定条件删除

  1. // 根据指定的过滤器判断匹配的元素是否在集合内:Predicate 接口主要用来判断一个参数是否符合要求。
  2. public boolean removeIf(Predicate<? super E> filter) {
  3. Objects.requireNonNull(filter); // 指定的过滤器的非null判断
  4. // figure out which elements are to be removed 找出要删除的元素
  5. // any exception thrown from the filter predicate at this stage 在这阶段抛出的任何异常都不会使得集合发生改变
  6. // will leave the collection unmodified
  7. int removeCount = 0; // 删除数目
  8. final BitSet removeSet = new BitSet(size); // BitSet是一种特殊类型的数组来保存位值,其中数组大小会随需要增加
  9. final int expectedModCount = modCount; // 记录修改次数
  10. final int size = this.size;
  11. // 这个循环主要是为了记录需要删除的元素数目
  12. for (int i=0; modCount == expectedModCount && i < size; i++) {
  13. @SuppressWarnings("unchecked")
  14. final E element = (E) elementData[i];
  15. if (filter.test(element)) {
  16. removeSet.set(i); // 通过 removeSet 来记录需要删除的集合下标
  17. removeCount++; // 删除数目进行累加
  18. }
  19. }
  20. if (modCount != expectedModCount) { // 正常情况下这两个值应该是相等的,不相等说明有了并发修改,则抛出异常
  21. throw new ConcurrentModificationException();
  22. }
  23. // shift surviving elements left over the spaces left by removed elements
  24. // 通过遍历使用未删除的元素替换已删除元素,[i] 代表未删除的元素下标,[j] 代表被替换的元素下标
  25. final boolean anyToRemove = removeCount > 0;
  26. if (anyToRemove) {
  27. final int newSize = size - removeCount; // 记录删除后的新的容量
  28. for (int i=0, j=0; (i < size) && (j < newSize); i++, j++) {
  29. i = removeSet.nextClearBit(i); // 找出未删除元素的下标 [i]
  30. elementData[j] = elementData[i]; // 使用未删除的元素 [i] 替换对应位置 [j] 的元素
  31. }
  32. for (int k=newSize; k < size; k++) { // 将下标从 [k] 到之后的位置的元素赋值为null
  33. elementData[k] = null; // Let gc do its work
  34. }
  35. this.size = newSize;
  36. if (modCount != expectedModCount) { // 出现并发修改时抛出异常
  37. throw new ConcurrentModificationException();
  38. }
  39. modCount++; // 修改次数累加
  40. }
  41. return anyToRemove;
  42. }

源码刨析:

  • 这个方法

    1. removeIf
    支持指定一个过滤器(Predicate)来删除指定的若干元素。
  • 在这个方法中用到了:

    1. final BitSet removeSet = new BitSet(size);
    BitSet 是一种特殊类型的数组,它只能记录两种状态:
    1. 0
    1. 1
    ,可以用来代表
    1. 有没有
    1. 是与否
    等数据。在这块是为了存储需要
    1. 删除
    的元素的下标。
  • 这里使用一个和集合的

    1. size
    一样容量的 BitSet 来对应每一个集合元素的下标,方便后续处理。
  • 通过

    1. for (int i=0; modCount == expectedModCount && i < size; i++)
    这个循环匹配集合中需要删除的元素,用其下标来为
    1. removeSet
    对应位置 [i] 的状态位的值为
    1. true
  • 到了

    1. if (modCount != expectedModCount)
    这一步就是常规的并发修改的检查,如果出现并发修改则直接抛出异常。
    1. anyToRemove
    的值大于零,也就是匹配到有需要删除的元素,则开始执行数据的删除操作。
  • 通过

    1. for (int i=0, j=0; (i < size) && (j < newSize); i++, j++)
    这个循环来处理,利用BitSet的
    1. i = removeSet.nextClearBit(i);
    获取得到下一个值为
    1. false
    的下标值,也就是获取未被标记删除的元素下标。
  • 进行数据替换:

    1. elementData[j] = elementData[i];
    ,上一步已经获取到未被标记删除的元素下标 [i],在这一步就可以顺次替换掉 [j] 位置的元素,这样一来就能保证未被标记删除的元素最终都集中在集合
    1. 前面连续部分的位置
    ,也就是在下标
    1.  

以上就是Java集合框架概览之ArrayList源码分析的详细内容,更多关于Java集合框架概览之ArrayList源码分析的资料请关注九品源码其它相关文章!