Java 集合的迭代操作 Iterator

几种实现 列出如下  

 1 import java.util.*;
 2 
 3 /**
 4  * Created by wojia on 2017/6/13.
 5  */
 6 public class IteratorDemo {
 7         public static void main(String args[]){
 8             List list = new ArrayList();
 9             list.add("A");
10             list.add("B");
11             list.add("C");
12             list.add("D");
13             System.out.println(list);
14             /*list 集合的迭代操作*/
15             //1. for loop
16             for(int index = 0 ; index < list.size() ; index++){ //it's method which declared as size() , not a variable  size.
17                 Object temp = list.get(index);
18                 System.out.print(temp);
19 
20             }
21             System.out.println();
22 
23             //2. for - each loop
24             for(Object ele : list){
25                 System.out.print(ele);
26             }
27             System.out.println();
28 
29             //3. Use iterator
30             /**list.iterator will return an iterator Object*/
31             Iterator iterator = list.iterator();
32             while(iterator.hasNext()){
33                 System.out.print(iterator.next());//next()is a method
34             }
35 
36             //4. Use for loop
37             /**
38              * this method is the best ,better than while loop , because of the gc 
39              * */
40             for(Iterator it = list.iterator();iterator.hasNext();){
41                 System.out.print(it.next());
42             }
43 
44         }
45 
46     }

  

posted on 2017-06-13 21:53  吸毒术士柯震东  阅读(153)  评论(0编辑  收藏  举报

导航