这是ArrayList
的实施细节。
ArrayList
由数组支持。对具有负索引的数组的访问会抛出ArrayIndexOutOfBoundsException
,因此不必通过ArrayList
类的代码进行明确测试。
在另一方面,如果用非负折射率是的范围外访问ArrayList
的ArrayList
(即> =的ArrayList
的大小),特定的检查,在下面的方法中,进行这抛出IndexOutOfBoundsException
:
/**
* Checks if the given index is in range. If not, throws an appropriate
* runtime exception. This method does *not* check if the index is
* negative: It is always used immediately prior to an array access,
* which throws an ArrayIndexOutOfBoundsException if index is negative.
*/
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
这检查是必要的,因为所提供的索引可以是背衬阵列的有效索引(如果它比ArrayList
的电流容量较小),所以访问与索引背衬阵列> = ArrayList
的大小不一定会抛出异常。
ArrayIndexOutOfBoundsException
是子类的IndexOutOfBoundsException
,这意味着它是正确的说ArrayList
的get
方法对于这两个负指数抛出IndexOutOfBoundsException
和指数> =列表的大小。
注意,不像ArrayList
,LinkedList
抛出IndexOutOfBoundsException
为负和非负的指标,因为它不是由数组支持,因此它不能依赖于一个阵列上扔负指数异常:
private void checkElementIndex(int index) {
if (!isElementIndex(index))
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
/**
* Tells if the argument is the index of an existing element.
*/
private boolean isElementIndex(int index) {
return index >= 0 && index < size;
}
一个非常明显的区别是'-1'永远不会是一个有效的索引,而'1'将是(如果一个列表至少有两个条目)。 –
* ArrayIndexOutOfBoundException *是** IndexOutOfBoundException的子类** - 最重要的一点。另一个子类是* StringIndexOutOfBoundsException *。 –