Three ways to traverse the list interface

1  /* 
2  * Three ways to traverse the list interface
 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          // The first way
 15  //         Iterator it = list. iterator();
16  //         while(it.hasNext()){
 17  //             System.out.println(it.next());
 18  //         }
 19          
20          // Reduce the scope of variables and use memory efficiently 
21          for (Iterator it = list.iterator();it.hasNext();){
 22              System.out.println(it.next());
 23          }
 24          
25          System.out.println("--------- ----" );
 26          // Simplified writing of iterator 
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 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324647438&siteId=291194637