简体   繁体   中英

Why are not all elements removed from my ArrayList<Integer>?

I'm a newbie studying Android programming using Android Studio, and I have a problem. I try to remove all elements in this list, but at the end, it says the size is 5. Why?

This is my code:

ArrayList<Integer> arr = new ArrayList<Integer>(10);
for(int i=1;i<=10;i++){
    arr.add(i);
}

for(int i=0;i<arr.size();i++) {
    arr.remove(i);
}

Toast.makeText(getApplicationContext(),
    arr.size()+" ",
    Toast.LENGTH_LONG).show();

Oh you know why?

Because when i++ it will get bigger right? But each time you remove the length of the arraylist changed. It will get smaller

i
0 1 2 3 4 5
arraylist size
9 8 7 6 5 4

Hence it only remove 5 of them 10-5 = 5 in the end the list size is 5

The removal loop will only execute 5 times as the condition i < arr.size() is evaluated on each loop iteration, and arr.size() is getting smaller each time. So i gets bigger, arr.size() gets smaller, and they meet in the middle.

To fix it, iterate backwards:

for (int i = arr.size(); --i >= 0;) {
    arr.remove(i);
}

Or change it to:

while (arr.size() > 0) {
    arr.remove(0);
}

Or, more efficiently, remove the loop and call arr.clear(); instead.

Note that confusingly, calling remove with an int removes the element at that position, whereas calling add with an int is adding that value as an Integer . If you want to remove the value , call remove((Integer)i); .

It's common mistake made by a lot of newbie developers. I did it in past as well. Those answers below explain why. It's dangerous to loop through array by size and remove items inside the loop. The array.clear() is the easiest one, but if you need to make extra work on each element before removing, you could use Iterators as was discussed in this thread

Calling remove in foreach loop in Java

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM