ArrayList中的add(index, element)方法分析

本文解析了ArrayList的add方法实现原理,解释了为何插入位置不能超过当前元素数量的原因,并探讨了这种设计背后的逻辑。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

问题引入:今天在使用ArrayList的add(index, element)方法向list中插入数据的时候出现数组越界异常,感觉很奇怪,list不是支持动态扩展的吗?为什么会出现越界的情况呢?

 

有了问题,当然要首先查看JDK源码咯:

 

/**
     * 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).
     *
     * @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++;
    }
   /**
     * A version of rangeCheck used by add and addAll.
     */
    private void rangeCheckForAdd(int index) {
        if (index > size || index < 0)
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
    }

 源码中一目了然,在往list中插入数据之前会先对你插入的位置作检查,插入的位置只能是[0, list.size()],


 

另外要说明的是,这个size在ArrayList中的定义是:

 

   /**

     * The size of the ArrayList (the number of elements it contains).

     * @serial

     */

    private int size;

即list实际包含元素的个数。目前为止我们还只是知道了JDK中就是这样设计的,但是为什么这样设计:为什么插入元素的位置不能是大于size呢?

 

以下是个人理解:

前面已经知道了size是表示list中实际包含的元素的个数,并且,在调用add方法成功往list添加元素的时候size会加1,在调用remove方法成功从list中删除一个数据的时候size会减1。 

那么如果支持向大于size中插入数据,那么插入成功之后会将size++,但是实际上list实际要维护的list的元素个数就不只是size了。

假如原来list中有3个元素,对应的存储位置是0,1,2,现在我向第5个位置插入数据,那么成功之后size大小变为4;但是3、4位置上的元素是什么呢?我使用下标遍历list的时候怎么知道这个位置有没有元素呢?所以这势必会导致很多问题出现,所以对插入位置进行检查是有意义的。

 

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值