Remove odd elements from ArrayList while iterating

java

Solution

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++;
    }

Problem

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?

Original source