zoukankan      html  css  js  c++  java
  • 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     }
  • 相关阅读:
    40+个性鲜明的企业网站展示
    20+富有创意的BuddyPress网站
    TopFreeTheme精选免费模板【20130827】
    10本最新的Android开发电子书免费下载
    20个最棒的英文电子书免费下载网站
    合法免费下载电子书的站点整理收藏
    2013年19个最棒的HTML5网站模板免费下载
    [NUnit] discover test finished: 0 found issue
    完全数
    IP
  • 原文地址:https://www.cnblogs.com/oablog/p/7044193.html
Copyright © 2011-2022 走看看