/**
* 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));
}
From: jdk/ArrayList.java at jdk8-b120 · openjdk/jdk · GitHub
If we write the following code, both indexes are out of bounds, but the exception types are different.
import java.util.ArrayList;
import java.util.List;
public class Test {
public static void main(String[] args) {
List<String> list = new ArrayList<>();
list.add("");
try {
list.get(-1);
} catch (Exception e) {
e.printStackTrace();
}
try {
list.get(1);
} catch (Exception e) {
e.printStackTrace();
}
}
}
The output is as follows:
java.lang.ArrayIndexOutOfBoundsException: -1
at java.util.ArrayList.elementData(ArrayList.java:424)
at java.util.ArrayList.get(ArrayList.java:437)
at Test.main(Test.java:11)
java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.rangeCheck(ArrayList.java:659)
at java.util.ArrayList.get(ArrayList.java:435)
at Test.main(Test.java:17)
Related question:
- Why does
rangeCheckForAdd
method in thejava.util.ArrayList
check for negative index? - Why doesn't
java.util.Arrays.ArrayList
do index out-of-bounds checking?
What confuses me is why their implementations are inconsistent? Are these methods written by different people with their own programming style? In other words, if out-of-bounds exceptions will eventually fire, then there is no need to check.