Looping through and arraylist and removing elements at specified index

前端 未结 6 1480
栀梦
栀梦 2020-12-21 04:02

I was trying an exercise where I would add 1000 elements to an arraylist and then remove them systematically from the list again(by specifying the index). The idea behind th

6条回答
  •  一整个雨季
    2020-12-21 04:18

    This happens because you are altering the indexes by removing. If you remove element 0, element 1 now becomes element 0. Now when you next remove 1, that is what used to be element 2 and what was element 1 still exists at index 0.

    The easiest way to avoid this is to loop backwards from end to beginning.

    alternatively, you could just keep removing index 0 until the ArrayList is empty.

提交回复
热议问题