問題是這樣的,看下邊這段代碼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的增加數(shù)據(jù)中,只有這個增加方法增加了這個判斷語句
關于ArrayList源碼的問題,大佬快進
墨色風雨
2018-08-13 11:10:36