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 reverse() method returns a raw Iterator (not Iterator). When used in the for-each loop, Java cannot determine the type parameter for the iterator. For-each loops require an array or a generic Iterable. Raw Iterator doesn't implement Iterable properly, so this fails to compile. The fix is to return Iterator.