list接口的三种遍历方式

 1 /*
 2  * list接口的三种遍历方式
 3  * 
 4  */
 5 public class ListDemo2 {
 6 
 7     public static void main(String[] args) {
 8         List list = new ArrayList();
 9         
10         list.add("hello");
11         list.add("hello2");
12         list.add("hello2");
13         list.add("hello");
14         //第一种方式
15 //        Iterator it = list.iterator();
16 //        while(it.hasNext()){
17 //            System.out.println(it.next());
18 //        }
19         
20         //缩小变量的作用域,有效的利用内存
21         for(Iterator it = list.iterator();it.hasNext();){
22             System.out.println(it.next());
23         }
24         
25         System.out.println("-------------");
26         //迭代器的简化写法
27         for (Object o : list) {
28             System.out.println(o);
29         }
30         
31         System.out.println("-------------");
32         //第三种:普通for循环
33         for(int i = 0;i<list.size();i++){
34             System.out.println(list.get(i));
35         }
36         
37     }
38 }

猜你喜欢

转载自www.cnblogs.com/star521/p/8882501.html