1 package day5.lesson2;
2
3 import java.util.ArrayList;
4 import java.util.Iterator;
5 import java.util.List;
6
7 /*
8 2.7 案例-List集合存储学生对象三种方式遍历
9 创建一个存储学生对象的集合,存储3个学生对象,使用程序实现在控制台遍历该集合
10 */
11 public class StudentDemo {
12 public static void main(String[] args) {
13 List<Student> list = new ArrayList<>();
14 Student s1 = new Student("zhangsan", 22);
15 Student s2 = new Student("lisi", 24);
16 Student s3 = new Student("wangwu", 23);
17 list.add(s1);
18 list.add(s2);
19 list.add(s3);
20
21 //迭代器:集合特有的遍历方式
22 Iterator<Student> it = list.iterator();
23 while (it.hasNext()){
24 Student stu = it.next();
25 System.out.println(stu.getName() + "," + stu.getAge());
26 }
27
28 //普通for:带有索引的遍历方式
29 for (int i=0; i<list.size(); i++){
30 Student stu = list.get(i);
31 System.out.println(stu.getName() + "," + stu.getAge());
32 }
33
34 //增强for:最方便的遍历方式
35 for (Student stu: list){
36 System.out.println(stu.getName() + "," + stu.getAge());
37 }
38 }
39 }
1 package day5.lesson2;
2
3 public class Student {
4
5 private String name;
6 private int age;
7
8 public Student() {
9 }
10
11 public Student(String name, int age) {
12 this.name = name;
13 this.age = age;
14 }
15
16 public void setName(String name) {
17 this.name = name;
18 }
19
20 public void setAge(int age) {
21 this.age = age;
22 }
23
24 public String getName() {
25 return name;
26 }
27
28 public int getAge() {
29 return age;
30 }
31 }