[英]Is this snippet unnecessary in the source code of Arraylist.remove(int index)?
Here's the source code: 这是源代码:
Removes the element at the specified position in this list.
删除此列表中指定位置的元素。 Shifts any subsequent elements to the left (subtracts one from their indices).
将任何后续元素向左移位(从索引中减去一个)。 Parameters: index the index of the element to be removed Returns: the element that was removed from the list Throws: java.lang.IndexOutOfBoundsException
参数:index要删除的元素的索引返回:从列表中删除的元素抛出: java.lang.IndexOutOfBoundsException
public E remove(int index) {
rangeCheck(index);
modCount++;
E oldValue = elementData(index);
int numMoved = size - index - 1;
if (numMoved > 0)
System.arraycopy(elementData, index+1, elementData, index,
numMoved);
elementData[--size] = null; // Let gc do its work
return oldValue;
}
My question is: 我的问题是:
As the rangeCheck(index) has already guarantee that index < size , is it necessary to check that if (numMoved > 0)
? 由于rangeCheck(index)已经保证index <size ,是否有必要检查
if (numMoved > 0)
?
numMoved
can be 0 (if you remove the last element by calling list.remove(list.size()-1)
), in which case no arraycopy
is required. numMoved
可以为0(如果通过调用list.remove(list.size()-1)
删除最后一个元素),在这种情况下不需要arraycopy
。 Therefore the if (numMoved > 0)
is necessary. 因此
if (numMoved > 0)
是必要的。
删除列表的最后一个元素时, index
等于size - 1
,在这种情况下numMoved
为0且不需要System.arraycopy
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.