Java ArrayList avoiding IndexOutOfBoundsException

i got a short question.

ArrayList<T> x = (1,2,3,5)

int index = 6
if (x.get(6) == null) {
    return 0;
}

Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 6, Size: 4

How can I avoid this? I just want to check if there is something in the array with index 6. If there is (null)/(nothing there) i want to return 0.

Jon Skeet
people
quotationmark

Just use the size of the list (it's not an array):

if (x.size() <= index || x.get(index) == null) {
    ...
}

Or if you want to detect a valid index with a non-null value, you'd use:

if (index < x.size() && x.get(index) != null) {
    ...
}

In both cases, the get call will not be made if the first part of the expression detects that the index is invalid for the list.

Note that there's a logical difference between "there is no element 6" (because the list doesn't have 7 elements) and "there is an element 6, but its value is null" - it may not be important to you in this case, but you need to understand that it is different.

people

See more on this question at Stackoverflow