Issue
I'm getting periodic crash reports on the following line of code:
myList.get(myList.size() - 1)
Which wouldn't be that interesting if not for the stack trace:
java.lang.ArrayIndexOutOfBoundsException: length=22; index=-1
java.util.ArrayList.get ArrayList.java:439
com.myapp.ope.api.ApiManager$2.onResponse ApiManager.java:215
retrofit2.DefaultCallAdapterFactory$ExecutorCallbackCall$1.lambda$onResponse$0$DefaultCallAdapterFactory$ExecutorCallbackCall$1 DefaultCallAdapterFactory.java:89
retrofit2.-$$Lambda$DefaultCallAdapterFactory$ExecutorCallbackCall$1$hVGjmafRi6VitDIrPNdoFizVAdk.run Unknown Source:6
Which seems to imply myList
has a length of 22. So how is the index calculated at -1 (which means .size()
would have reported 0)?
Solution
The ArrayList
in Java 8 only checks if the index is greater than its size, throwing an IndexOutOfBoundsException
if so. Otherwise array[index]
is used to access the desired element of the array used to store the list elements. This will throw an ArrayIndexOutOfBoundsException
if the index is out of range, using the length of the array in the message. The array will be substituted by larger one if needed, but it will never be changed to a smaller one - so it is normal that the array is larger than required.
In Java 9, the index check was changed: it uses Objects.checkIndex()
, which checks both limits and uses the size of the list for the Exception message.
Answered By - user16320675
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.