0

When developing an Android App I faced with the situation when there is no element in non-empty Java ArrayList with zero index. The reason of the problem is somehow connected with the fact that I sometimes delete the zero-indexed items with list.remove(0) method when the list is non-empty. Nevertheless the specification on the remove method says that it "Shifts any subsequent elements to the left (subtracts one from their indices)". So I can't understand what is the reason of situations (it happens sometimes) when I get a non-empty list with no zero element (the first element has index 1). I can see no zero element both by getting an NullPointerException on list.get(0) and by seeing ArrayList content in Android Studio Debugger.

Debugging screenshot - ArrayList's shapshot with no zero item in Android Studio

3
  • Can you post the code and tell us what line of it gets the error? Commented Jun 14, 2016 at 19:03
  • Possible duplicate of Get specific ArrayList item Commented Jun 14, 2016 at 20:09
  • It's not a duplicate. I call list.get(0) to get the zero-indexed element Commented Jun 16, 2016 at 11:50

1 Answer 1

0

The first element in a not empty list has always index 0. As stated by documentation:

Lists (like Java arrays) are zero based

What you see in your debugging screenshot is simply a method of visualization for elements presents in the list. What is called 1 is not the index, but the position. So 1 stay for first element.

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

2 Comments

But when I try to call list.get(0) I get exception in this case where 0 is really supposed to be the index. I would like to remind that the situation with no 0-element happens rarely (sometimes, not every time). In common case (normal case) just after calling list.remove(0) we get the list shifted and starting with 0-element and thus we can call get(0) but sometimes happens what was described above.
Check size of list calling list.size(). If 0th element doesn't exists the list is empty.

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.