案例:List集合存储学生对象用三种方式遍历

 

public class ListDemo {
    public static void main(String[] args) {
        //创建List集合对象
        List<Student> list = new ArrayList<Student>();

        //创建学生对象
        Student s1 = new Student("旭旭宝宝",21);
        Student s2 = new Student("大马猴",22);
        Student s3 = new Student("任怡旭",30);

        //把学生添加到集合
        list.add(s1);
        list.add(s2);
        list.add(s3);

        //遍历集合
        //方式1.迭代器遍历
        Iterator<Student> it = list.iterator();
        while (it.hasNext()){
            Student s = it.next();
            System.out.println(s.getName()+","+s.getAge());
        }
        System.out.println("--------");

        //方式2.普通for循环索引遍历
        for (int i = 0; i<list.size(); i++){
            Student s = list.get(i);
            System.out.println(s.getName()+","+s.getAge());
        }
        System.out.println("--------");

        //方式3.增强for循环遍历
        for (Student s : list){
            System.out.println(s.getName()+","+s.getAge());
        }
    }
}

运行结果:

 

posted @ 2020-04-08 10:26  硬盘红了  阅读(607)  评论(0编辑  收藏  举报