Beyond indexed for loops, Java collections implement Iterable—enhanced for-each and explicit Iterator support safe removal during iteration (with iterator's remove, not collection's while looping).
Iterator pattern
Iterator<String> it = items.iterator();
while (it.hasNext()) {
String s = it.next();
}
forEach (Java 8+)
items.forEach(s -> System.out.println(s));
Important interview questions and answers
- Q: Can you remove during enhanced for?
A: Not safely withlist.remove(i)—use iterator.remove or removeIf. - Q: Iterable vs Iterator?
A: Iterable provides iterator(); Iterator traverses elements.
Self-check
- Which loop syntax works on any Iterable?
- Why is concurrent modification dangerous?