Looping through and arraylist and removing elements at specified index

前端 未结 6 1486
栀梦
栀梦 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:14

    Look through you loop where you removing elements again. Every time you remove and element the value returned by al.size() reduces, while you index increases. That means you will only be iterating half the time you want to.

    The fix would be to do this.

    int size = al.size();
    for(int index = 0; index < size; index++ ) {
    

    then do work. this way the size does not change.

    The other thing to remember is that when you remove something from the arraylist at index 0, index 1 will become index 0. So it might be better to iterate from

    int index = al.size(); index >=0 ; index--
    

提交回复
热议问题