Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove odd elements from ArrayList while iterating

Tags:

java

I have an ArrayList of Strings and I'm trying to remove the odd elements of the ArrayList, i.e. list.remove(1), list.remove(3), list.remove(5) etc.

This is the code I'm attempting to use which throws up an IllegalStateException error:

int i = 0;
    for (Iterator<String> it = words.iterator(); it.hasNext(); )
    {
        if (i % 2 != 0 && it.hasNext())
        {
            it.remove();
        }
        i++;
    }

Is there a better (working) way to do this?

like image 913
Rishad Bharucha Avatar asked Dec 26 '22 06:12

Rishad Bharucha


1 Answers

int i = 0;
    for (Iterator<String> it = words.iterator(); it.hasNext(); )
    {
        it.next(); // Add this line in your code
        if (i % 2 != 0)
        {
            it.remove();
        }
        i++;
    }
like image 96
prasanth Avatar answered Jan 09 '23 04:01

prasanth