2017-04-06 109 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