如果我们创建一个ArrayList像下面的虚拟,并get使用-1和1作为参数调用方法.然后我们得到以下内容output:
对于测试案例1:它会抛出 ArrayIndexOutOfBoundException
对于测试案例2:它会抛出IndexOutOfBoundException.
List list = new ArrayList();
list.get(-1); //Test Case 1
list.get(1); // Test Case 2
Run Code Online (Sandbox Code Playgroud)请解释为什么这两者有区别?
这是一个实现细节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));
}
Run Code Online (Sandbox Code Playgroud)
此检查是必要的,因为提供的索引可能是后备阵列的有效索引(如果它小于当前容量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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
94 次 |
| 最近记录: |