Iterator by hand, iterator.remove and removeIf
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.
Using an explicit Iterator, remove every negative number from [3, -1, 4, -1, 5, -9] and print the list and how many were removed.
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.
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
How does a for-each loop over a List work under the hood?
What is a fail-fast iterator and how is it implemented?
Why is fail-fast described as "best effort"? Give an example where no exception is thrown.
What are the correct ways to remove elements from a collection while iterating over it?
Expected output
removed 35
removed 18
after iterator.remove: [72, 90, 41]
after removeIf: [72, 90, 41]
after set in loop: [100, 95, 46]