Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java ArrayList avoiding IndexOutOfBoundsException

Tags:

java

arraylist

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.

like image 254
user3717963 Avatar asked Jun 14 '14 16:06

user3717963


People also ask

How to avoid IndexOutOfBoundsException in Java?

In order to avoid the java. lang. ArrayIndexOutOfBoundsException, you should always do the bound check before accessing array element e.g. Always remember that the array index starts at 0 and not 1 and an empty array has no element in it.

Is IndexOutOfBoundsException a runtime exception?

The ArrayIndexOutOfBoundsException is a runtime exception in Java that occurs when an array is accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

What causes Java Lang IndexOutOfBoundsException?

The IndexOutOfBoundsException is thrown when attempting to access an invalid index within a collection, such as an array , vector , string , and so forth. It can also be implemented within custom classes to indicate invalid access was attempted for a collection.

What is the difference between ArrayIndexOutOfBoundsException and IndexOutOfBoundsException?

IndexOutOfBoundsException is the super class of ArrayIndexOutOfBoundsException (thrown when accessing invalid index in a array) and StringIndexOutOfBoundsException (thrown when accessing invalid index in a String).


2 Answers

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.

like image 150
Jon Skeet Avatar answered Sep 22 '22 11:09

Jon Skeet


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

like image 40
Ashish Bhatia Avatar answered Sep 20 '22 11:09

Ashish Bhatia