问题是这样的,看下边这段代码
public boolean addAll(int index, Collection<? extends E> c) {
rangeCheckForAdd(index);
Object[] a = c.toArray(); int numNew = a.length; ensureCapacityInternal(size + numNew); // Increments modCount int numMoved = size - index; if (numMoved > 0) System.arraycopy(elementData, index, elementData, index + numNew, numMoved); System.arraycopy(a, 0, elementData, index, numNew); size += numNew; return numNew != 0; }
这个方法一开始先调用了rangeCheckForAdd(index)方法,这个方法内部是这样的
private void rangeCheckForAdd(int index) {
if (index > size || index < 0)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
也就是一开始就判断了index与size的大小问题,那么为什么下边这段代码还需要加个大于0的判断呢
int numMoved = size - index;
if (numMoved > 0)
System.arraycopy(elementData, index, elementData, index + numNew,
numMoved);
ArrayList的增加数据中,只有这个增加方法增加了这个判断语句
LEATH