Java的List集合三种遍历方式

本文详细介绍Java中List集合的创建及使用方法,包括实体类定义、元素添加与三种遍历方式:基本for循环、增强for循环及Iterator迭代器。通过实例演示如何高效运用List集合。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  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     }

 

转载于:https://www.cnblogs.com/oablog/p/7044193.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值