这里的异常是 IndexOutOfBoundsException:
public static void main(String[] args) {
List<Integer> elements = new ArrayList<>();
elements.add(10);
int firstElmnt = elements.get(1);
System.out.println(firstElmnt);
}
但这里的异常是 ArrayIndexOutOfBoundsException:
public static void main(String[] args) {
List<Integer> elements = new ArrayList<>();
elements.add(10);
int firstElmnt = elements.get(-1);
System.out.println(firstElmnt);
}
这是否意味着对于负数我们会得到 IndexOutOfBoundException?
最佳答案
List
的 Javadoc 指定抛出 IndexOutOfBoundsException
:
if the index is out of range (index < 0 || index >= size())
由于 ArrayIndexOutOfBoundsException
是 IndexOutOfBoundsException
的子类,因此 List
接口(interface)的实现可以选择抛出该异常而不是基类IndexOutOfBoundsException
类。
对于超出范围的正索引,此代码会抛出异常:
private void rangeCheck(int index) {
if (index >= size)
throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
}
另一方面,对于负索引,通过使用负索引访问后备数组会引发异常:
E elementData(int index) {
return (E) elementData[index];
}
这使得 ArrayList 实现无需显式检查索引是否为负数。
关于java - ArrayIndexOutOfBoundException 和 IndexOutOfBoundsException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49738182/