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

Oleg
  • 1
  • 2

1 Answers1

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.

Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
  • 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. – Oleg Jun 14 '16 at 19:30
  • Check size of list calling list.size(). If 0th element doesn't exists the list is empty. – Davide Lorenzo MARINO Jun 14 '16 at 19:32