- Executors
-
Learn
Learn Python Runnable examples, NumPy, pandas, and more Learn AI / Machine LearningNeural networks, ML and LLMs from scratch Learn C & C++ Pointers, memory, STL, and modern C++ Learn C#C# basics, OOP, LINQ, async, and .NET exercises Learn MatplotlibLine, bar, scatter and pie charts with live visualizers Learn RustOwnership, traits, error handling, and threads Learn GoSlices, interfaces, goroutines, and channels Python Algorithms Search, sorting, recursion, and visualizers O(n) C & C++ Algorithms Compare algorithms implemented in C and C++ Coding for Kids Learn to code by playing!
- QuizzesNew
- ChallengesNew
- For TeachersNew
- Updates
- Buy me a coffee
Java Iterators & ConcurrentModificationException Quiz
This hard Java quiz is about changing a collection while you iterate over it. You will see when the for-each loop throws ConcurrentModificationException (and the odd case where it does not), and practice the safe ways: Iterator.remove(), removeIf(), ListIterator and CopyOnWriteArrayList.
Sample question
Question 1 of 10What happens when you run this?
import java.util.ArrayList;
import java.util.List;
public class Main {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>(List.of(1, 2, 3, 4));
for (Integer n : list) {
if (n == 2) list.remove(n);
}
System.out.println(list);
}
}
Show the answer
A. ConcurrentModificationException The for-each loop uses a hidden iterator. Removing through the list itself changes its modification count, and the iterator's next next() call notices and throws ConcurrentModificationException.
What this quiz covers
- Why removing inside a for-each loop throws
Iterator.remove()and its rulesremoveIf()as the simple fix- Index loops that skip elements
ListIterator.add()andCopyOnWriteArrayList
Questions people ask
Do I need an account?
No. Anyone can play. Sign in to keep your XP, streak, badges and history.
Can I retake it?
Yes. Your best score is kept, and the questions and answers are shuffled each time.