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)

细心的小伙伴已经注意到了上面的那段代码有一行专门标注了行号,而执行的结果的异常行号刚好是我标注的那一行,不难得出 就是在: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.      /**
  14.          * Constructs an empty list with the specified initial capacity.
  15.          * 根据指定的初始化容量构造一个空的 list 集合
  16.          * @param initialCapacity the initial capacity of the list 初始化的容量
  17.          * @throws IllegalArgumentException if the specified initial capacity
  18.          * is negative 如果指定的容量为负数则抛出异常
  19.          */
  20.      public ArrayList(int initialCapacity) {
  21.          if (initialCapacity > 0) {
  22.              this.elementData = new Object[initialCapacity];
  23.          } else if (initialCapacity == 0) {
  24.              this.elementData = EMPTY_ELEMENTDATA;
  25.          } else {
  26.              throw new IllegalArgumentException(“Illegal Capacity: “+
  27.                      initialCapacity);
  28.          }
  29.      }

简单分析一下这段源码:

  • ArrayList 底层采用普通的数组来存储数据,通过 elementData 这一成员变量来存储集合的数据。
  • 在实例化是当传入的参数大于零,则实例化一个对应容量的 Object 数组并赋值给我们的 elementData 成员变量。
  • 在实例化是当传入的参数等于零,安装默认的 EMPTY_ELEMENTDATA 空数组赋值给elementData 成员变量。
  • 在实例化是当传入的参数小于零,则抛出指定的 IllegalArgumentException 异常信息。

小贴士: 细心的小伙伴会注意到我们的 elementData成员变量使用了 transient 关键字修饰,这里简单科普一下:

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

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

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

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

三、添加元素

ArrayList添加元素

现在到了我们的重头戏,从执行结果反馈来看,抛出异常的位置就在这: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.  
  13.          ensureCapacityInternal(size + 1); // Increments modCount!! 是否扩容的判断
  14.          System.arraycopy(elementData, index, elementData, index + 1,
  15.                      size  index); // 数组拷贝
  16.          elementData[index] = element; // 将待添加的元素放入指定的位置
  17.          size++; // 集合的实际大小累加
  18.      }
  19.          /**
  20.          * The size of the ArrayList (the number of elements it contains).
  21.          * ArrayList 的成员变量,保存了已有元素的数量
  22.          * @serial
  23.          */
  24.      private int size;
  25.      /**
  26.          * A version of rangeCheck used by add and addAll.
  27.          */
  28.      private void rangeCheckForAdd(int index) {
  29.          if (index > size || index < 0)
  30.              throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  31.      }

源码刨析:

  • 首先看rangeCheckForAdd(index);这一行,这个方法主要是检查待插入的 index 索引是否越界或者非法。 经过缜密分析(debug ),发现正是这里的检查抛出的异常,导致我们出师未捷身先死/(ㄒoㄒ)/~~,第一步就被绊倒了。
  • 既然判断的是 index 和 size 的大小,那么我们回过头看一下:private int size; 这个玩意,通过其注释我们得知这个成员变量保存了已有元素的数量,那么问题就很明显了:我们初始化后的集合虽然已经有了一个指定容量的数组,但是并没有实际元素,所以 size 依然为0。不难得出结论:==这种指定位置插入元素的方法必须从下标0开始顺次插入元素,你敢隔空插入它就敢死给你看!==

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

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

源码刨析:

  • 这一方法:private void ensureCapacityInternal(int minCapacity)主要是为了检查集合是否可以满足指定的最小数量的元素的要求。
  • 如果满足的话,则只需要将修改次数:modCount++ 累加就完事。
  • 如果容量不够用了,则需要进行扩容,那么就需要调用 grow(int minCapacity) 方法来执行扩容任务。
  • 通过 int newCapacity = oldCapacity + (oldCapacity >> 1); 方法将原来的容量扩容1.5倍,后续的两个 if 判断考虑了 newCapacity 溢出的情况,最终保证了 newCapacity 必然为正数。

小贴士: 上面的:grow(int minCapacity)方法用到了移位运算符。 java中有三种移位运算符: << :左移运算符,num << 1,相当于num乘以2。 >> :右移运算符,num >> 1,相当于num除以2。 >>>:无符号右移,忽略符号位,空位都以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.  
  11.          return elementData(index); // 按下标获取元素
  12.      }
  13.      /**
  14.          * Checks if the given index is in range. If not, throws an appropriate
  15.          * runtime exception. This method does *not* check if the index is
  16.          * negative: It is always used immediately prior to an array access,
  17.          * which throws an ArrayIndexOutOfBoundsException if index is negative.
  18.          */
  19.      private void rangeCheck(int index) {
  20.          if (index >= size)
  21.              throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
  22.      }

源码刨析:

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

五、删除元素

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.  
  13.          modCount++; // 修改次数累加
  14.          E oldValue = elementData(index);
  15.  
  16.          int numMoved = size  index  1; // 计算需要移动的元素数量,指的就是当前删除位置之后的元素数量
  17.          if (numMoved > 0)
  18.              System.arraycopy(elementData, index+1, elementData, index,
  19.                      numMoved); // 重新进行数据拷贝
  20.          elementData[–size] = null; // clear to let GC do its work 将数组末尾空缺出来的位置引用置为null,便于GC
  21.  
  22.          return oldValue;
  23.      }

源码刨析:

  • 首先就是进行下标越界的检查,然后就是修改次数的累加以及获取待删除的旧数据。
  • 这块:int numMoved = size - index - 1; 主要是计算一下当前待删除元素之后有多少需要移动的元素数量。
  • 这个 numMoved 的值可能为 0 ,比如说当前集合就一个元素,在删除下标为 0 的时候,numMoved 的值就为 0 ,所以接下来做了一次 if 是否大于零的判断,如果为 true,则执行数组的拷贝,将需要处理的元素全部往前移动一位。
  • 上一步移动完元素之后,数组的最后一个位置就空缺出来了,然后就通过 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 (== 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.      }

源码刨析:

  • 首先根据待删除的元素是否为 null 进行分别处理。
  • 如果待删除的元素是 null 的话,则遍历所有数组元素和 null 进行匹配,匹配到第一个的话则执行删除,直接返回true。
  • 如果不是,则遍历所有数组元素和待删除元素进行 equals 匹配,匹配到第一个的话则执行删除,直接返回true。
  • 对于 fastRemove 这个方法的话,笔者认为在上一个指定下标删除的时候可以直接调用这个方法的。

小贴士: 由上述源码可以得出一个结论:==如果你想删除一个 ArrayList 中的 所有 null 元素,调用一次 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=”Collection.html#optional-restrictions” rel=”external nofollow” rel=”external nofollow” >optional</a>)
  10.          * @throws NullPointerException if this list contains a null element and the
  11.          * specified collection does not permit null elements
  12.          * (<a href=”Collection.html#optional-restrictions” rel=”external nofollow” rel=”external nofollow” >optional</a>),
  13.          * or if the specified collection is null
  14.          * @see Collection#contains(Object)
  15.          */
  16.      public boolean removeAll(Collection<?> c) {
  17.          Objects.requireNonNull(c); // 对 c 集合进行空判断
  18.          return BATchRemove(c, false); // 执行批量删除
  19.      }
  20.      // 批量删除方法
  21.      private boolean batchRemove(Collection<?> c, boolean complement) {
  22.          final Object[] elementData = this.elementData;
  23.          int r = 0, w = 0;
  24.          boolean modified = false; // 操作结果标识
  25.          try {
  26.          // 通过遍历原集合,将不符合删除条件的 [r] 位置的元素替换掉 [w] 位置的元素,并将 [w] 累加。
  27.              for (; r < size; r++) // 每次循环 r++
  28.                  if (c.contains(elementData[r]) == complement) // 如果待删除的集合不包含有原集合的元素
  29.                      elementData[w++] = elementData[r]; // 则用原集合当前下标位置 [r] 的元素覆盖掉下标位置为 [w] 的元素
  30.                      // 并将 [w] 累加。
  31.          } finally {
  32.              // Preserve behavioral compatibility with AbstractCollection,
  33.              // even if c.contains() throws.
  34.              // 只有在抛出异常时:r != size ,那么此时需要将未比对的元素拼接在已经处理过的元素后面
  35.              if (!= size) {
  36.                  System.arraycopy(elementData, r,
  37.                      elementData, w,
  38.                      size  r);
  39.                  w += size  r; // 重新设置 [w] 的值,因为在下一步会将 [w] 之后的元素设置为null,此时的 [r] 为抛出异常位置
  40.              }
  41.              // 在极端情况下,如果待删除集合和原集合的元素完全无交集,则 `w == size`,这种情况下无需对原集合进行任何操作。
  42.              if (!= size) {
  43.                  // clear to let GC do its work
  44.                  for (int i = w; i < size; i++)
  45.                      elementData[i] = null; // 将 [w] 之后的元素全部赋值为 null。
  46.                  modCount += size  w; // 对 modCount 进行重新设置
  47.                  size = w;
  48.                  modified = true;
  49.              }
  50.          }
  51.          return modified;
  52.      }
  53.      // 集合是否包含指定的元素
  54.      public boolean contains(Object o) {
  55.          return indexOf(o) >= 0; // 遍历集合查找指定元素
  56.      }

源码刨析:

  • 首先对传入的参数集合进行 null 判断,如果为空则直接抛出异常。
  • 接下来就是通过 batchRemove 方法执行批量删除。
  • 这个:batchRemove方法首先会遍历原集合,使用其 [r] 位置元素去匹配在待删除集合是否存在:
  • 如果不存在,说明该元素并不是要删除元素,则:if (c.contains(elementData[r]) == complement) 返回true,此时的原集合的 [r] 位置元素需要覆盖到原集合的 [w] 位置,此时 [w] 进行累加,方便下次进行覆盖。
  • 在循环完毕后,最终的结果就是:原集合的 [w] 位置之前的元素都是需要保留下来的。
  • 在 finally 代码块中:进行的第一个 if (r != size) 判断是为了在出现异常时(此时r != size)单独将后续未处理完的 [r] 之后数据拷贝到原集合的 [r] 之后,保证数据的完整性。另外还需要重新计算 [w] 的值。
  • 在这一步:if (w != size) 判断是为了将 [w] 之后的重叠需要删除的数据赋值为 null,最后修改 modCount 和集合的大小 size 的值。
  • 总之按博主的理解,这个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; (< size) && (< 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.  
  42.          return anyToRemove;
  43.      }

源码刨析:

  • 这个方法 removeIf 支持指定一个过滤器(Predicate)来删除指定的若干元素。
  • 在这个方法中用到了:final BitSet removeSet = new BitSet(size); BitSet 是一种特殊类型的数组,它只能记录两种状态:01,可以用来代表有没有是与否等数据。在这块是为了存储需要删除的元素的下标。
  • 这里使用一个和集合的 size 一样容量的 BitSet 来对应每一个集合元素的下标,方便后续处理。
  • 通过for (int i=0; modCount == expectedModCount && i < size; i++) 这个循环匹配集合中需要删除的元素,用其下标来为 removeSet 对应位置 [i] 的状态位的值为true
  • 到了if (modCount != expectedModCount) 这一步就是常规的并发修改的检查,如果出现并发修改则直接抛出异常。
  • 在 anyToRemove 的值大于零,也就是匹配到有需要删除的元素,则开始执行数据的删除操作。
  • 通过 for (int i=0, j=0; (i < size) && (j < newSize); i++, j++)这个循环来处理,利用BitSet的i = removeSet.nextClearBit(i);获取得到下一个值为false的下标值,也就是获取未被标记删除的元素下标。
  • 进行数据替换:elementData[j] = elementData[i];,上一步已经获取到未被标记删除的元素下标 [i],在这一步就可以顺次替换掉 [j] 位置的元素,这样一来就能保证未被标记删除的元素最终都集中在集合前面连续部分的位置,也就是在下标 [newSize] 之前。
  • 通过这部分:for (int k=newSize; k < size; k++) 进行遍历 [k] 之后的元素,执行 elementData[k] = null; 把下标 [k] 以及之后的位置元素赋值为null,便于下一次的 GC 。
  • 最后再次进行并发修改的检查以及集合的修改次数的累加。

小贴士: 对于这个方法使用这里给一个简单的例子: 假设有一个字符串集合 list:[“Google”,”Runoob”,”Taobao”,”Facebook”],我们想删除所有带有 ”oo“的元素; 则可以:list.removeIf(e -> e.contains("oo"));,最终的集合就变为:[“Taobao”]。

5.5 下标区间删除

  1.      /**
  2.          * Removes from this list all of the elements whose index is between
  3.          * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
  4.          * 删除下标区间 [fromIndex]至[toIndex]之间的元素,包含[fromIndex] 但是不包含 [toIndex] 。
  5.          * Shifts any succeeding elements to the left (reduces their index).
  6.          * 将删除区间之后的集合元素统一左移动。
  7.          * This call shortens the list by {@code (toIndex – fromIndex)} elements.
  8.          * (If {@code toIndex==fromIndex}, this operation has no effect.)
  9.          * 如果[fromIndex]和[toIndex]相等,则对集合无影响。
  10.          * @throws IndexOutOfBoundsException if {@code fromIndex} or
  11.          * {@code toIndex} is out of range
  12.          * ({@code fromIndex < 0 ||
  13.          * fromIndex >= size() ||
  14.          * toIndex > size() ||
  15.          * toIndex < fromIndex})
  16.          */
  17.      protected void removeRange(int fromIndex, int toIndex) {
  18.          modCount++; // 修改次数累加
  19.          int numMoved = size  toIndex; // 需要移动的元素数量,也就是待删除区间的末尾之后的元素数量。
  20.          System.arraycopy(elementData, toIndex, elementData, fromIndex,
  21.                      numMoved); // 用删除区间的末尾之后的元素拷贝至删除区间的元素进行覆盖。
  22.  
  23.          // clear to let GC do its work
  24.          int newSize = size  (toIndexfromIndex); // 计算新的集合的长度,方便后续进行多余数组元素的置空
  25.          for (int i = newSize; i < size; i++) {
  26.              elementData[i] = null; // 将后半部分的多余位置的元素赋值为 null,方便GC。
  27.          }
  28.          size = newSize; // 重新设置集合的大小
  29.      }

源码刨析:

  • 这个方法可以指定删除一段下标区间的所有元素。
  • 首先进行修改次数的累加:modCount++;,然后计算删除区间的结束下标 [toIndex] 之后的元素数量,也就是 numMoved ,这部分元素需要往前移动来覆盖待删除区间的位置。
  • 以数组拷贝的方式:System.arraycopy 将后半部分有效元素往前移动覆盖掉删除区间的位置。
  • 重新计算集合的大小:int newSize = size - (toIndex-fromIndex),方便后续将后半部分空缺的位置的数据进行无效化。
  • 通过循环遍历将后部分无效的集合元素进行赋值 null 的操作,方便 GC 回收。
  • 重新设置集合的大小:size = newSize;

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

标签

发表评论