Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through and arraylist and removing elements at specified index

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 this is to compare the performance of the LinkedList to the ArrayList.

int totalObjects = 0;
    for(int i = 0; i < 1000; i++)
    {
        totalObjects += 1;
        al.add("Object " + totalObjects);

    }
     System.out.println("The Arraylist size is " + al.size());

If i do the following only half of the elements gets removed...why is that?

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

        al.remove(index);

    }
    System.out.println("The Arraylist size after removal is " + al.size());

kind regards Arian

like image 574
Arianule Avatar asked Nov 28 '22 11:11

Arianule


2 Answers

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.

like image 71
James Montagne Avatar answered Dec 09 '22 15:12

James Montagne


Be aware that you can remove all the elements at once by simply using the clear() method. In your code, the problem is that the list is being modified at the same time that you're iterating over it, effectively decreasing its size, so the index < al.size() condition fails. Try this instead:

for (int index = 0, n = al.size(); index < n; index++)
    al.remove(0);

Alternatively, this solution removes elements at the end, making it more efficient (it's no longer necessary to copy elements around):

for (int idx = al.size() - 1; idx >= 0; idx--)
    al.remove(idx);
like image 42
Óscar López Avatar answered Dec 09 '22 13:12

Óscar López