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.
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.
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.
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.
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).
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.
check size of arraylist. if size is less that 6 then return 0 else return value
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With