Hi everyone,
I'm learning Java collections and ran into an issue when removing elements from an ArrayList inside a for-loop.
Example:
ArrayList<Integer> numbers = new ArrayList<>();
numbers.add(1);
numbers.add(2);
numbers.add(3);
numbers.add(4);
for (int i = 0; i < numbers.size(); i++) {
if (numbers.get(i) % 2 == 0) {
numbers.remove(i);
}
}
System.out.println(numbers);
Among Us
I expected all even numbers to be removed, but the behavior becomes confusing when there are multiple matching elements.
Can someone explain why this happens and what the recommended approach is in modern Java? Should I use an Iterator, removeIf(), or another solution?
Thanks!
eliradelorca
Level 1
Why does my Java for-loop skip elements after removing items from an ArrayList?
Under discussion
Comments
- Popular
- New
- Old
You must be signed in to leave a comment
This page doesn't have any comments yet