Multiple choice technology programming languages

Given: 11. public static Iterator reverse(List list) { 12. Collections.reverse(list); 13. return list.iterator(); 14. } 15. public static void main(String[] args) { 16. List list = new ArrayList(); 17. list.add(” 1”); list.add(”2”); list.add(”3”); 18. for (Object obj: reverse(list)) 19. System.out.print(obj + “,”); 20. } ‘What is the result?

  1. 3,2, 1,

  2. 1, 2, 3,

  3. Compilation fails.

  4. The code runs with no output.

  5. An exception is thrown at runtime.

Reveal answer Fill a bubble to check yourself
C Correct answer
Explanation

The code has a compilation error. In the for-each loop at line 18, reverse(list) is called, which returns Iterator. However, the for-each syntax expects either an array or an Iterable (Collection), not an Iterator directly. You cannot use a for-each loop with an Iterator - you must use hasNext()/next() instead. This is a syntax error that prevents compilation.

AI explanation

The method reverse(List list) returns an Iterator, not an Iterable. Java's enhanced for-loop (for (Object obj : reverse(list))) requires its expression to implement Iterable, so that a fresh Iterator can be obtained internally — it cannot iterate directly over an Iterator, since an Iterator already represents mid-traversal state and doesn't itself provide an iterator() method. Passing an Iterator where an Iterable is required is a type mismatch caught at compile time, so 'Compilation fails' is correct. The other options assume the loop runs and produce various orderings or exceptions, but none of that matters because the code never gets past compilation.