温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

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

发布时间:2023-03-27 14:22:50 来源:亿速云 阅读:70 作者:iii 栏目:开发技术

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

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

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

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

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

好啦,揭晓谜底:

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的初始化

先从集合的初始化入手:

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

上源码(硬菜):

	/**
     * The array buffer into which the elements of the ArrayList are stored.
     * The capacity of the ArrayList is the length of this array buffer. Any
     * empty ArrayList with elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA
     * will be expanded to DEFAULT_CAPACITY when the first element is added.
     */
    transient Object[] elementData; // non-private to simplify nested class access
    /**
     * Shared empty array instance used for empty instances.
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     * Constructs an empty list with the specified initial capacity.
     * 根据指定的初始化容量构造一个空的 list 集合
     * @param  initialCapacity  the initial capacity of the list 初始化的容量
     * @throws IllegalArgumentException if the specified initial capacity
     *         is negative 如果指定的容量为负数则抛出异常
     */
    public ArrayList(int initialCapacity) {
        if (initialCapacity > 0) {
            this.elementData = new Object[initialCapacity];
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            throw new IllegalArgumentException("Illegal Capacity: "+
                                               initialCapacity);
        }
    }

简单分析一下这段源码:

  • ArrayList 底层采用普通的数组来存储数据,通过 elementData 这一成员变量来存储集合的数据。

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

  • 在实例化是当传入的参数等于零,安装默认的 EMPTY_ELEMENTDATA 空数组赋值给elementData 成员变量。

  • 在实例化是当传入的参数小于零,则抛出指定的 IllegalArgumentException 异常信息。

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

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

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

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

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

三、添加元素

ArrayList添加元素

现在到了我们的重头戏,从执行结果反馈来看,抛出异常的位置就在这:list.add(1, "hello");,让我们磨刀霍霍向源码一探究竟。

    /**
     * Inserts the specified element at the specified position in this
     * list. Shifts the element currently at that position (if any) and
     * any subsequent elements to the right (adds one to their indices).
     * 向 ArrayList 中指定的位置插入指定的元素,如果当前位置已经有元素,则会将该位置之后的所有元素统一往后移一位。
     * @param index index at which the specified element is to be inserted 待插入的索引位置
     * @param element element to be inserted 待插入的元素
     * @throws IndexOutOfBoundsException {@inheritDoc} 下标越界异常
     */
    public void add(int index, E element) {
        rangeCheckForAdd(index); // 越界检查

        ensureCapacityInternal(size + 1);  // Increments modCount!! 是否扩容的判断
        System.arraycopy(elementData, index, elementData, index + 1,
                         size - index); // 数组拷贝
        elementData[index] = element; // 将待添加的元素放入指定的位置
        size++; // 集合的实际大小累加
    }
     /**
     * The size of the ArrayList (the number of elements it contains).
     *  ArrayList 的成员变量,保存了已有元素的数量
     * @serial
     */
    private int size;
    
    /**
     * A version of rangeCheck used by add and addAll.
     */
    private void rangeCheckForAdd(int index) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

源码刨析:

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

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

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

	// 判断是否需要扩容
    private void ensureCapacityInternal(int minCapacity) {
        ensureExplicitCapacity(calculateCapacity(elementData, minCapacity));
    }

    private void ensureExplicitCapacity(int minCapacity) {
        modCount++; // 修改次数累加

        // overflow-conscious code
        if (minCapacity - elementData.length > 0)
            grow(minCapacity);
    }
    /**
     * 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
     */
    private void grow(int minCapacity) {
        // overflow-conscious code
        int oldCapacity = elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);// 将原容量扩容至原来的1.5倍,以本例来说就是扩容至:6+3=9
        if (newCapacity - minCapacity < 0)
            newCapacity = minCapacity; //取 newCapacity 和 minCapacity 的最大值赋值给 newCapacity,考虑了溢出的情况
        if (newCapacity - MAX_ARRAY_SIZE > 0)
            newCapacity = hugeCapacity(minCapacity);
        // minCapacity is usually close to size, so this is a win:
        elementData = Arrays.copyOf(elementData, newCapacity);
    }
    /**
     * 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 :申请的数组长度超过了虚拟机的限制
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;
    
    private static int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) // overflow 溢出检查
            throw new OutOfMemoryError();
        return (minCapacity > MAX_ARRAY_SIZE) ? // 如果申请的最小容量比数组的容量上限还大则容量设置为:
            Integer.MAX_VALUE : // Integer.MAX_VALUE,否则设置为:数组容量上限(MAX_ARRAY_SIZE)
            MAX_ARRAY_SIZE;
    }

源码刨析:

  • 这一方法: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补齐。

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

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

源码刨析:

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

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

四、ArrayList获取元素

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

    /**
     * Returns the element at the specified position in this list.
     * 返回集合指定位置的元素
     * @param  index index of the element to return 要返回的元素下标
     * @return the element at the specified position in this list 指定下标的元素
     * @throws IndexOutOfBoundsException {@inheritDoc} 下标越界异常
     */
    public E get(int index) {
        rangeCheck(index); // 索引越界检查

        return elementData(index); // 按下标获取元素
    }
    /**
     * Checks if the given index is in range.  If not, throws an appropriate
     * runtime exception.  This method does *not* check if the index is
     * negative: It is always used immediately prior to an array access,
     * which throws an ArrayIndexOutOfBoundsException if index is negative.
     */
    private void rangeCheck(int index) {
        if (index >= size)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

源码刨析:

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

五、删除元素

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

5.1 指定下标删除

    /**
     * Removes the element at the specified position in this list.
     * Shifts any subsequent elements to the left (subtracts one from their
     * indices).
     * 删除特定位置的集合元素,将该元素之后的所有元素往前挪一位。
     * @param index the index of the element to be removed 待删除的元素下标
     * @return the element that was removed from the list 返回已删除的元素
     * @throws IndexOutOfBoundsException {@inheritDoc} 下标越界异常
     */
    public E remove(int index) {
        rangeCheck(index); // 下标越界检查

        modCount++; // 修改次数累加
        E oldValue = elementData(index);

        int numMoved = size - index - 1; // 计算需要移动的元素数量,指的就是当前删除位置之后的元素数量
        if (numMoved > 0)
            System.arraycopy(elementData, index+1, elementData, index,
                             numMoved); // 重新进行数据拷贝
        elementData[--size] = null; // clear to let GC do its work 将数组末尾空缺出来的位置引用置为null,便于GC

        return oldValue;
    }

源码刨析:

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

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

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

  • 上一步移动完元素之后,数组的最后一个位置就空缺出来了,然后就通过 elementData[--size] = null; 将该位置的引用置为 null 便于GC处理。

5.2 按元素删除

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

源码刨析:

  • 首先根据待删除的元素是否为 null 进行分别处理。

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

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

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

小贴士: 由上述源码可以得出一个结论:==如果你想删除一个 ArrayList 中的 所有 null 元素,调用一次 remove(null); 是无法删除全部的null元素的。==

5.3 批量删除

    /**
     * Removes from this list all of its elements that are contained in the
     * specified collection.
     * 按给定的特定元素集合去删除当前集合的匹配元素。
     * @param c collection containing elements to be removed from this list 包含待删除元素的删除
     * @return {@code true} if this list changed as a result of the call
     * @throws ClassCastException if the class of an element of this list
     *         is incompatible with the specified collection
     * (<a href="Collection.html#optional-restrictions" rel="external nofollow"  rel="external nofollow" >optional</a>)
     * @throws NullPointerException if this list contains a null element and the
     *         specified collection does not permit null elements
     * (<a href="Collection.html#optional-restrictions" rel="external nofollow"  rel="external nofollow" >optional</a>),
     *         or if the specified collection is null
     * @see Collection#contains(Object)
     */
    public boolean removeAll(Collection<?> c) {
        Objects.requireNonNull(c); // 对 c 集合进行空判断
        return batchRemove(c, false); // 执行批量删除
    }
    // 批量删除方法
    private boolean batchRemove(Collection<?> c, boolean complement) {
        final Object[] elementData = this.elementData;
        int r = 0, w = 0;
        boolean modified = false; // 操作结果标识
        try {
        	// 通过遍历原集合,将不符合删除条件的 [r] 位置的元素替换掉 [w] 位置的元素,并将 [w] 累加。
            for (; r < size; r++) // 每次循环 r++
                if (c.contains(elementData[r]) == complement) // 如果待删除的集合不包含有原集合的元素
                    elementData[w++] = elementData[r]; // 则用原集合当前下标位置 [r] 的元素覆盖掉下标位置为 [w] 的元素
                    // 并将 [w] 累加。
        } finally {
            // Preserve behavioral compatibility with AbstractCollection,
            // even if c.contains() throws.
            // 只有在抛出异常时:r != size ,那么此时需要将未比对的元素拼接在已经处理过的元素后面
            if (r != size) {
                System.arraycopy(elementData, r,
                                 elementData, w,
                                 size - r);
                w += size - r; // 重新设置 [w] 的值,因为在下一步会将 [w] 之后的元素设置为null,此时的 [r] 为抛出异常位置
            }
            // 在极端情况下,如果待删除集合和原集合的元素完全无交集,则 `w == size`,这种情况下无需对原集合进行任何操作。
            if (w != size) {
                // clear to let GC do its work
                for (int i = w; i < size; i++)
                    elementData[i] = null; // 将 [w] 之后的元素全部赋值为 null。
                modCount += size - w; // 对 modCount 进行重新设置
                size = w;
                modified = true;
            }
        }
        return modified;
    }
    // 集合是否包含指定的元素
    public boolean contains(Object o) {
        return indexOf(o) >= 0; // 遍历集合查找指定元素
    }

源码刨析:

  • 首先对传入的参数集合进行 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 特定条件删除

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

        return anyToRemove;
    }

源码刨析:

  • 这个方法 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 下标区间删除

    /**
     * Removes from this list all of the elements whose index is between
     * {@code fromIndex}, inclusive, and {@code toIndex}, exclusive.
     * 删除下标区间 [fromIndex]至[toIndex]之间的元素,包含[fromIndex] 但是不包含 [toIndex] 。
     * Shifts any succeeding elements to the left (reduces their index).
     * 将删除区间之后的集合元素统一左移动。
     * This call shortens the list by {@code (toIndex - fromIndex)} elements.
     * (If {@code toIndex==fromIndex}, this operation has no effect.)
     * 如果[fromIndex]和[toIndex]相等,则对集合无影响。
     * @throws IndexOutOfBoundsException if {@code fromIndex} or
     *         {@code toIndex} is out of range
     *         ({@code fromIndex < 0 ||
     *          fromIndex >= size() ||
     *          toIndex > size() ||
     *          toIndex < fromIndex})
     */
    protected void removeRange(int fromIndex, int toIndex) {
        modCount++; // 修改次数累加
        int numMoved = size - toIndex; // 需要移动的元素数量,也就是待删除区间的末尾之后的元素数量。
        System.arraycopy(elementData, toIndex, elementData, fromIndex,
                         numMoved); // 用删除区间的末尾之后的元素拷贝至删除区间的元素进行覆盖。

        // clear to let GC do its work
        int newSize = size - (toIndex-fromIndex); // 计算新的集合的长度,方便后续进行多余数组元素的置空
        for (int i = newSize; i < size; i++) {
            elementData[i] = null; // 将后半部分的多余位置的元素赋值为 null,方便GC。
        }
        size = newSize; // 重新设置集合的大小
    }

源码刨析:

  • 这个方法可以指定删除一段下标区间的所有元素。

  • 首先进行修改次数的累加:modCount++;,然后计算删除区间的结束下标 [toIndex] 之后的元素数量,也就是 numMoved ,这部分元素需要往前移动来覆盖待删除区间的位置。

  • 以数组拷贝的方式:System.arraycopy 将后半部分有效元素往前移动覆盖掉删除区间的位置。

  • 重新计算集合的大小:int newSize = size - (toIndex-fromIndex),方便后续将后半部分空缺的位置的数据进行无效化。

  • 通过循环遍历将后部分无效的集合元素进行赋值 null 的操作,方便 GC 回收。

  • 重新设置集合的大小:size = newSize;

以上就是“Java集合框架概览之ArrayList源码分析”这篇文章的所有内容,感谢各位的阅读!相信大家阅读完这篇文章都有很大的收获,小编每天都会为大家更新不同的知识,如果还想学习更多的知识,请关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI