IndexOutOfBoundsException(outOfBoundsMsg(index))异常:
在使用ArrayList中add方法加入数据,如果指定的index位置超出list.size则会throw IndexOutOfBoundsException(outOfBoundsMsg(index));代码如下:
ArrayList<String> list = new ArrayList<>();
list.add("tttt");
list.add(2,"rrrr");
IndexOutOfBoundsException(outOfBoundsMsg(index))异常:
在使用ArrayList中set方法对list数据进行更新,如果指定的index位置大于等于list.size则会throw IndexOutOfBoundsException(outOfBoundsMsg(index));代码如下:
ArrayList<String> list = new ArrayList<>();
list.add("tttt");
list.set(1,"qqqq");
值得注意的是使用add(int index, E element)方法对指定位置进行添加数据,并没有删除原index位置的数据,而是将原index位置数据及之后的数据整体向后移动,再将element数据赋值给list中的index位置上。具体代码:
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++;
}