package day5.lesson2; import java.util.ArrayList; import java.util.Iterator; import java.util.List; /* 2.3 案例-List集合存储学生对象并遍历 创建一个存储学生对象的集合,存储3个学生对象,使用程序实现在控制台遍历该集合 */ public class ListDemo2 { public static void main(String[] args) { List<Student> list = new ArrayList<>(); Student s1 = new Student("sam", 12); Student s2 = new Student("amy", 11); Student s3 = new Student("tom", 12); 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()); } //遍历方式2 for(int i=0; i<list.size(); i++){ Student stu = list.get(i); System.out.println(stu.getName() + "," + stu.getAge()); } } }
package day5.lesson2; public class Student { private String name; private int age; public Student() { } public Student(String name, int age) { this.name = name; this.age = age; } public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public int getAge() { return age; } }