Java的List集合三種遍歷方式

  List集合在Java平常開發中是必不可少的,要懂得運用各類各樣的方法能夠大大提升咱們開發的效率,固然是要在對應的需求上使用合適的方法纔會事半功倍。java

  List集合:this

    List<Example> exampleList = new ArrayList<>();spa

  實體類(Example):code

 1 package ListExample;
 2 
 3 import java.io.Serializable;
 4 
 5 /**
 6  * Created by Max on 2017-06-18.
 7  */
 8 public class Example implements Serializable{
 9 
10     private String id;
11     private String name;
12     private String pass;
13 
14     public String getId() {
15         return id;
16     }
17 
18     public void setId(String id) {
19         this.id = id;
20     }
21 
22     public String getName() {
23         return name;
24     }
25 
26     public void setName(String name) {
27         this.name = name;
28     }
29 
30     public String getPass() {
31         return pass;
32     }
33 
34     public void setPass(String pass) {
35         this.pass = pass;
36     }
37 }

  exampleList添加元素:對象

    public List<Example> getListExample(){
        List<Example> exampleList = new ArrayList<>();
        for(int i=0;i<=3;i++){
            Example example = new Example();
            example.setId(String.valueOf(i));
            example.setName("第"+String.valueOf(i)+"個");
            example.setPass("密碼:"+String.valueOf(i));
            exampleList.add(example);
        }
        return exampleList;
    }

  第一種:List集合遍歷的最基礎的方式:for循環,指定下標長度,根據List集合的size()長度,for循環遍歷;blog

//i的操做,小於或者小於等於集合的長度,根據本身的需求,能夠
    for(int i=0;i<exampleList.size();i++){
        Example example = exampleList.get(i);//獲取每個Example對象
        String name = example.getName();
        System.out.print("第"+i+"個=?"+name);
    }

  第二種:很是簡單的寫法:直接根據List集合的長度自動遍歷,可是不能操做第幾個;開發

1 for(Example example : exampleList){
2        String name = example.getName();//直接操做Example對象
3        System.out.print(("Name:"+name);
4     }

   第三種:利用迭代器Iterator遍歷:也是直接根據List集合的自動遍歷,直到遍歷完整個List;get

1 for(Iterator iterators = exampleList.iterator();iterators.hasNext();){
2         Example example = (Example) iterators.next();//獲取當前遍歷的元素,指定爲Example對象
3         String name = example.getName();
4         System.out.print("Name:"+name);
5     }
相關文章
相關標籤/搜索