It has always been thought that only arrays will have an ArrayIndexOutOfBoundsException array subscript out-of-bounds exception, and even if ArrayList is empty, ArrayList.get(0) will also return null. Today I suddenly discovered that ArrayList will also throw an out-of-bounds exception IndexOutOfBoundsException. Careful students may find that these two exceptions are still different.
ArrayList subscript out of bounds exception
Specially tested the array and ArrayList, and recorded it:
1. If the array is within its capacity range, the value will not throw an exception, and null will be returned. Only if the value is not within the capacity, the out-of-bounds exception ArrayIndexOutOfBoundsException will be thrown.
The array is within its capacity, and the value will not throw an exception
Array subscript out of bounds exception
2. Even if the capacity of ArrayList is initialized, IndexOutOfBoundsException will be thrown when the subscript has no elements. When we look at the get method of ArrayList, we will find that when the obtained subscript is greater than or equal to size, an IndexOutOfBoundsException will be thrown.
ArrayList get method source code
If the subscript is greater than or equal to size, an exception is thrown
3. An array is maintained in ArrayList. If it is not restricted here, it should be the same as an array. Within its capacity range, the value will not throw an exception.
An array is maintained in ArrayList
ArrayList get method source code
The get method of ArrayList is ultimately an array value
4. ArrayList.get(-1) will not trigger the previous IndexOutOfBoundsException, but it is not within the range of the array capacity, and throws the same exception ArrayIndexOutOfBoundsException as the array subscript out of bounds.
ArrayList.get(-1)
Sometimes it's interesting to look at the source code. If there is something wrong, I hope to correct it!