Вопрос

I'm using the enhance for loop in my android application to iterate over a list of Status Objects.

 for (Status stat : status)
timelineItems.add(new TimelineItem(stat));

This is generating the following IndexOutOfBoundsException: java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0

I realized that the this is happening is because the size of the ArrayList is 0 which means its empty. My question is why did it even enter the loop in the first place isn't the enhanced for created to guarantee that these problems don't occur and how to I stop it.

Это было полезно?

Решение

First of all: Don't use enhanced for loop on Android if you're using an ArrayList. It's slower than the regular one and uses more memory. For all other collections, it's OK.

What you're experiencing probably relates to non-synchronized modification of the collection. If the size suddenly changes while the loop is running, it'll cause errors like that one.

Другие советы

The only way this can happen is if somebody else (another thread) clears the collection while the enhanced for loop was executing. It identified that there was a zeroth element, but when it came to access it it had been deleted.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top