6

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.

1
  • 2
    You can put condition on the size of the list. Commented Jun 14, 2014 at 16:28

3 Answers 3

18

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.

Sign up to request clarification or add additional context in comments.

4 Comments

If x.size() == 6 then x.get(6) throws IndexOutOfBoundsException.
@AudriusMeškauskas: Good job that my code won't call x.get(6) in that situation then, isn't it? If x.size() == 6, then x.size() <= 6 will be true, so the second operand of the || won't be evaluated.
Still looks very twisted. Your own second example is much easier to read.
@AudriusMeškauskas: The second example is the inverse though - look at the OP's original code; he's trying to detect the absence of a non-null value. That's the case if either the index is out of range or the result is null. Yes, it could be written as if (index >= x.size() ...) if you'd prefer that, but it would still fundamentally be a condition of "if the index is out of range" vs the second snippet of "if the index is in range".
2

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

1 Comment

Less or equal (off by one).
0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.