2017-04-06 63 views
1

我看看ArrayList的源代碼,發現remove方法如下:的ArrayList remove方法

/** 
* Removes the element at the specified position in this list. 
* Shifts any subsequent elements to the left (subtracts one from their 
* indices). 
* 
* @param index the index of the element to be removed 
* @return the element that was removed from the list 
* @throws IndexOutOfBoundsException {@inheritDoc} 
*/ 
public E remove(int index) { 
    if (index >= size) 
     throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); 

    modCount++; 
    E oldValue = (E) elementData[index]; 

    int numMoved = size - index - 1; 
    if (numMoved > 0) 
     System.arraycopy(elementData, index+1, elementData, index, 
         numMoved); 
    elementData[--size] = null; // clear to let GC do its work 

    return oldValue; 
} 

爲什麼它不考慮這種情況,當指數< 0?

回答

0

在負折射率傳遞將失敗下列行:

E oldValue = (E) elementData[index]; 

具體而言,向下層elementData陣列的存取將與一些負折射率發生。這將導致ArrayIndexOutOfBoundsException被拋出,如文檔所述:

拋出以指示已使用非法索引訪問數組。索引或者是負數,或者大於或等於數組的大小。

因此,ArrayList#remove()實現不需要做任何額外的事情,因爲該語言已經可以處理負指數的情況。

然而,你可能想知道爲什麼代碼確實進行以下檢查,如果該指數大於尺寸較大

if (index >= size) 
    throw new IndexOutOfBoundsException(outOfBoundsMsg(index)); 

這種檢查,是因爲它是可能的索引elementData的範圍內,但是大於比實際列表/數組的邏輯大小。換句話說,底層數組的大小不會(通常不會)與列表中實際的條目數鎖定在一起。相反,JVM將根據需要根據列表的大小和用途增大或縮小數組。

+0

哇,很清楚。謝謝。 – jemy

+0

不能upvote.vote施放的聲望低於15的人是紀錄,但不要改變公開顯示的帖子得分 – jemy