문제

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