62,623
社区成员
发帖
与我相关
我的任务
分享 List a = new ArrayList();
for (int i=0;i <3;i++) {
a.add(i,"1");
}
// 运行完毕后,你最后添加的是 a.add(2,"1"); 而不是 3,"1", 所以异常了
a.add(4,"1");
public void add(int index, E element) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(
"Index: "+index+", Size: "+size);
ensureCapacity(size+1); // Increments modCount!!
System.arraycopy(elementData, index, elementData, index + 1,
size - index);
elementData[index] = element;
size++;
}
if (index > size || index < 0)
throw new IndexOutOfBoundsException(
"Index: "+index+", Size: "+size);