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?
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++;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With