Java ArrayList avoiding IndexOutOfBoundsException

I have 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.

+4
source share
3 answers

Just use the size of the list (this is not an array):

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

Or, if you want to define a valid index with a non-zero value, you should use:

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

In both cases, the call getwill not be made if the first part of the expression finds that the index is not valid for the list.

, " 6" ( 7 ) " 6, null" - , , .

+12

arraylist. , 6, 0 else

+2

First check the size of the list using size(), then check the index.

if (x.size() <= 6 || x.get(6) == null) {
    return 0;
}
0
source

Source: https://habr.com/ru/post/1544587/


All Articles