Command Palette

Search for a command to run...

Back to the lesson: Topic 2.7 — The Enhanced for Loop
Core Java · Example 4 of 4

Removing safely (and the silent skip)

for (Type item : collection) visits every element of an array or any Iterable (like a List) in order, with no index to get wrong. The loop variable is a copy of each element, and you must not add to or remove from a collection while walking it this way.

Change the code and press Run (Ctrl+Enter). Try to predict the output first, then break it on purpose and read the error. Your edits are saved and match the lesson page.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Given String[] words = {"java", "loop", "enhanced", "for"}, use for-each to find the longest word and the total number of letters.

02

Count how many times the letter l appears in "hello world, hello loops" using for-each over the characters.

03

Given List<Integer> nums = List.of(3, 8, 1, 9, 4), use for-each to build a new ArrayList containing only the numbers greater than 3, then print it.

Explain it without notes

01

What can the enhanced for loop iterate over, and what does the compiler turn it into?

02

Why doesn't for (int x : arr) x = 0; clear the array, while for (StringBuilder sb : arr) sb.setLength(0); does clear every builder?

03

Why does removing from an ArrayList inside a for-each loop throw ConcurrentModificationException, and how should you remove instead?

04

When must you use a classic for loop instead of for-each?

Removing safely (and the silent skip)
Sign in to run this example in your browser.

Expected output

visiting Ana
visiting Bob
Cy was never visited: [Ana, Cy]
Odds via iterator: [1, 3, 5]
Odds via removeIf: [1, 3, 5]