问题引入:今天在使用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的时候怎么知道这个位置有没有元素呢?所以这势必会导致很多问题出现,所以对插入位置进行检查是有意义的。
飞祥 2025-03-31
飞祥 2025-03-31
飞祥 2025-03-31
飞祥 2025-03-31
冰432 2025-03-31
黄蜂 2025-03-30
藏家282 2025-03-30
星辰大海本海 2025-03-30
小小猪 2025-03-30
许老头 2025-03-30