loop on list with remove [duplicate]
You need to use the iterator directly, and remove the item via that iterator.
for (Iterator<String> iterator = list.iterator(); iterator.hasNext(); ) {
String fruit = iterator.next();
if ("banane".equals(fruit)) {
iterator.remove();
}
System.out.println(fruit);
}
This seems a bit complicated, why not just do a normal for loop? I think it looks cleaner and won't throw this error. Just decriment i if you remove something. at least mine works, anyway. Those sort of auto-loops are more for coding convenience, I thought, so if they aren't being convenient then just don't use them.
for (int i = list.size() - 1; i>=0; i--) {
String fruit = list.get(i);
System.out.println(fruit);
if ("banane".equals(fruit)) {
list.remove(fruit);
}
}
In addition to using the Iterator
directly (which I would recommend) you can also store elements that you want to remove in a different list.
List<String> toRemove = new ArrayList<String>();
for (String fruit : list) {
if ("banane".equals(fruit))
toRemove.add(fruit);
System.out.println(fruit);
}
for (String fruit : toRemove) {
list.remove(fruit);
}
Mind you, I do not recommend this, it’s just an alternative. :)