SCJP 1.6版考題 198
出自 陳富國維基館
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? A. 3, 2, 1, B. 1, 2, 3, C. Compilation fails. D. The code runs with no output. E. An exception is thrown at runtime.
解答
Ans: C
解說:
Iterator不能用enhanced for,要用一般的for import java.util.*; class test{ public static Iterator reverse(List list){ Collections.reverse(list); return list.iterator(); } public static void main(String[] args){ List<String> list= new ArrayList<String>(); list.add("1"); list.add("2"); list.add("3"); Iterator it = reverse(list); for(;it.hasNext();) System.out.print(it.next().toString() + ", "); } }
|