Looping through and arraylist and removing elements at specified index

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

    it is normal that only half the list is empty, because when you remove elements from you list the size of the list decreases, but the index increases. And they meet up in the middle. If you really would like to remove elements one by one, and remove from the last to the first element. I suggest you use:

    while (!al.isEmpty())
    {
    
        al.remove(al.indexOf(al.size()-1));
    
    }
    

提交回复
热议问题