Java 遍历方式

一、遍历方式

  1. 迭代器
  2. 增强for循环
  3. 普通for循环

二、使用

迭代器:
public class IteratorMethod {
    public static void main(String[] args) {
        Collection<String> Coll=new ArrayList<>();
        Coll.add("姚明");
        Coll.add("科比");
        Coll.add("麦迪");
        Coll.add("艾弗森");
        Coll.add("欧文");
        System.out.println(Coll);
        System.out.println("=================");
        //多态 接口             实现类对象
        Iterator<String> it=Coll.iterator();

        while(it.hasNext()){
            String s=it.next();
            System.out.println(s);
        }
    }
}
增强for循环:
public class Student {
    private String name;
    private int age;

    public Student() {
    }
    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}
......{
List<Student> students = new ArrayList<>();
        students.add(new Student("科比",24));
        students.add(new Student("麦迪",13));
        students.add(new Student("乔丹",64));
        students.add(new Student("姚明",20));
        
        for(Student st : stufents) {
            System.out.println(st);
        }
}
普通for循环:
......
for (int i = 0; i < students.size(); i++) {
    Student s = students.get(i);
    System.out.println(s);
}
......
posted @ 2022-09-03 21:36  手可敲星辰脚驾七彩云  阅读(71)  评论(0编辑  收藏  举报