问题引入:今天在使用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的时候怎么知道这个位置有没有元素呢?所以这势必会导致很多问题出现,所以对插入位置进行检查是有意义的。
相关推荐
测试ArrayList和LinkedList的add方法
使用 Add方法在 ArrayList中添加元素(添加到ArrayList末尾) arrlist.Add("第一个元素"); arrlist.Add("第二个元素"); arrlist.Add("第三个元素"); foreach (int n in new int[3] { 0, 1, 2 }) { arrlist...
主要介绍了Java ArrayList.add 的实现方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
ArrayList基本功能实现与需求分析,详情代码信息可看博客内容
今天小编就为大家分享一篇关于Java ArrayList add(int index, E element)和set(int index, E element)两个方法的说明,小编觉得内容挺不错的,现在分享给大家,具有很好的参考价值,需要的朋友一起跟随小编来看看吧
主要给大家介绍了关于Java中ArrayList的removeAll方法的相关资料,文中通过示例代码介绍的非常详细,对大家具有一定的参考学习价值,需要的朋友们下面跟着小编一起来看看吧。
根据arraylist源码分析,自己编写了一个类似于arraylist集合的代码
在jni中操作arraylist对象,然后添加一个int型数据进去
详细介绍Java中ArrayList的使用方法以及与vector的对比
ArrayList的源码,写了一些自己的分析,包括jdk1.8的新特性
java的 ArrayList的使用与分析
集合ArrayList测试集合ArrayList测试集合ArrayList测试集合ArrayList测试集合ArrayList测试集合ArrayList测试
此方法是通过java提供的ArrayList方法对栈的实现;
java中ArrayList的用法
1.2ArrayList类常用方法【应用】 1.2.1构造方法 1.2.2成员方法 1.2.3示例代码 public class ArrayListDemo02 { public static void main(String[] args) { //创建集合 ArrayList<String> array = new ...
什么是ArrayList? 如何使用ArrayList? ArrayList重要的方法和属性?
我们可以通过IndexOf方法来查找对象在ArrayList中的位置 ArrayList alcollect = new ArrayList(); // Add individual items to the collection string str = learn csharp; alcollect.Add(str); //find position of...
pItemType Add(pItemType anItem); // Removes the item at the given index. Array is resize by one. void RemoveItemAtIndex(const int index); // Returns the item at the given index. pItemType ...
java中对ArrayList进行排序的方法参考
C语言版的ArrayList,具有ArrayList的基本方法增加、插入、删除、自动扩容等。