List集合遍历的三种方法
测试数据:
1 List<String> list = new ArrayList<String>(); 2 list.add("java"); 3 list.add("hello"); 4 list.add("se"); 5 list.add("ee");
1. 普通for循环
1 for (int i = 0; i < list.size(); i++) { 2 String s = (String)list.get(i); 3 System.out.println(s); 4 }
1 java 2 hello 3 se 4 ee
2. 增强for
1 for (String s : list) { 2 System.out.println(s); 3 }
1 java 2 hello 3 se 4 ee
3. 迭代器
1 Iterator it = list.iterator(); 2 while (it.hasNext()) { 3 System.out.println(it.next()); 4 }
1 java 2 hello 3 se 4 ee