Command Palette

Search for a command to run...

Back to the lesson: Topic 9.9 — Iterators and Fail-Fast Behaviour
Core Java · Example 2 of 4

Fail-fast in action, and the second-to-last quirk

The second loop is just as buggy as the first; it only got lucky with hasNext().

An Iterator walks a collection one element at a time and is what every for-each loop uses behind the scenes. Most java.util iterators are fail-fast: if the collection is structurally changed by anything other than the iterator itself, the next step throws ConcurrentModificationException.

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

Using an explicit Iterator, remove every negative number from [3, -1, 4, -1, 5, -9] and print the list and how many were removed.

02

Write an Iterable<Character> called Letters that yields the letters of a word in reverse order, and print "stack" reversed with a for-each loop.

03

Remove from a TreeMap<String, Integer> of {a=1, b=0, c=3, d=0} every entry whose value is 0 using a view, then double the remaining values with replaceAll. Print the map.

Explain it without notes

01

How does a for-each loop over a List work under the hood?

02

What is a fail-fast iterator and how is it implemented?

03

Why is fail-fast described as "best effort"? Give an example where no exception is thrown.

04

What are the correct ways to remove elements from a collection while iterating over it?

Fail-fast in action, and the second-to-last quirk
Sign in to run this example in your browser.

Expected output

visit asha
visit ben
CME after removing ben; list is now [asha, cara, dev]
visit asha
visit ben
visit cara
no exception, but dev was never visited: [asha, ben, dev]