2017-06-21 143 views
2

如果我们创建一个虚拟ArrayList像下面并调用get-11作为参数。然后,我们得到以下outputArrayIndexOutOfBoundException VS IndexOutOfBoundException

  • 测试用例1:它抛出ArrayIndexOutOfBoundException

  • 测试用例2:抛出IndexOutOfBoundException

    List list = new ArrayList(); 
    list.get(-1); //Test Case 1 
    list.get(1); // Test Case 2 
    

请解释为什么会出现这两者之间的区别?

+0

一个非常明显的区别是'-1'永远不会是一个有效的索引,而'1'将是(如果一个列表至少有两个条目)。 –

+0

* ArrayIndexOutOfBoundException *是** IndexOutOfBoundException的子类** - 最重要的一点。另一个子类是* StringIndexOutOfBoundsException *。 –

回答

6

这是ArrayList的实施细节。

ArrayList由数组支持。对具有负索引的数组的访问会抛出ArrayIndexOutOfBoundsException,因此不必通过ArrayList类的代码进行明确测试。

在另一方面,如果用非负折射率是的范围外访问ArrayListArrayList(即> =的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,这意味着它是正确的说ArrayListget方法对于这两个负指数抛出IndexOutOfBoundsException和指数> =列表的大小。

注意,不像ArrayListLinkedList抛出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; 
} 
+0

@ Eran-爵士Java文档说,如果索引小于0或大于或等于列表的大小,将会导致IndexOutOfBoundException。 –

+2

@Animal Javadoc说的是实话,因为'ArrayIndexOutOfBoundsException'是'IndexOutOfBoundException'的子类。 – Eran

+0

Ohhhh ...非常感谢... :) –

相关问题