What actually happens under the hood when you write a for-each loop over a Java collection?
A for-each loop like for (Book b : collection) is syntactic sugar that the Java compiler rewrites directly into Iterator pattern calls. The compiler requires collection to implement java.lang.Iterable, calls its iterator() method once to obtain an Iterator, and then translates the loop body into a while loop that calls hasNext() before each iteration and next() to obtain the current element and advance. This is why every standard Java collection — ArrayList, HashSet, TreeMap's keySet(), and so on — supports identical for-each syntax despite having completely different internal storage: they all implement the same Iterable contract, so the compiler can treat them uniformly regardless of what's actually happening underneath.
Ready to master this question?
Generate a complete walkthrough — background, the full answer in plain language, a working code example explained line by line, a real-world scenario, common mistakes, and how this same question gets asked in different ways.
Sign in to generate a response