Sitemap

Member-only story

I Removed an Element From ArrayList. The Next Element Escaped.

5 min read15 hours ago

--

Press enter or click to view image in full size

A Java developer wrote a loop to remove every occurrence of a particular number from an ArrayList.

The code compiled. It ran without throwing an exception. Even the output looked reasonable at first glance.

But one problem remained.

Some elements that should have been removed were still sitting inside the list.

The developer checked the condition, checked the remove() method, and checked the input data.

Everything looked correct.

So why was Java skipping elements?

Let’s start with a small example.

The loop that looked perfectly fine

List<Integer> numbers = new ArrayList<>(
List.of(10, 20, 20, 20, 30)
);

for (int i = 0; i < numbers.size(); i++) {
if (numbers.get(i) == 20) {
numbers.remove(i);
}
}
System.out.println(numbers);

What should the output be?

We’re removing every occurrence of 20.

So the expected result is:

[10, 30]

But the actual output is:

[10, 20, 30]

--

--

Backend Engineer
Backend Engineer

Written by Backend Engineer

Hey, I'm Josh! Full-stack dev into Java, Spring Boot, React & .NET. I write code, break things, fix them, and repeat. 😄