In-depth study of Java: source code analysis about List subscripts

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.

In-depth study of Java: source code analysis about List subscripts

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.

In-depth study of Java: source code analysis about List subscripts

The array is within its capacity, and the value will not throw an exception

In-depth study of Java: source code analysis about List subscripts

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.

In-depth study of Java: source code analysis about List subscripts

ArrayList get method source code

In-depth study of Java: source code analysis about List subscripts

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.

In-depth study of Java: source code analysis about List subscripts

An array is maintained in ArrayList

In-depth study of Java: source code analysis about List subscripts

ArrayList get method source code

In-depth study of Java: source code analysis about List subscripts

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.

In-depth study of Java: source code analysis about List subscripts

ArrayList.get(-1)

Sometimes it's interesting to look at the source code. If there is something wrong, I hope to correct it!

Guess you like

Origin blog.csdn.net/Java_Caiyo/article/details/110230304