Java的List集合三種遍歷方式


  List集合在Java日常開發中是必不可少的,要懂得運用各種各樣的方法可以大大提高我們開發的效率,當然是要在對應的需求上使用合適的方法才會事半功倍。

  List集合:

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

  實體類(Example):

 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循環遍歷;

//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;

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     }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM