user3717963
user3717963

Reputation: 189

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.

Upvotes: 6

Views: 12292

Answers (3)

Jon Skeet
Jon Skeet

Reputation: 1502066

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.

Upvotes: 18

Rakesh KR
Rakesh KR

Reputation: 6527

Check the size of the list first by using size(), then check for the index.

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

Upvotes: 0

Ashish Bhatia
Ashish Bhatia

Reputation: 51

check size of arraylist. if size is less that 6 then return 0 else return value

Upvotes: 2

Related Questions