List集合存储学生对象用三种方式遍历
需求:创建一个存储学生对象的集合,存储三个学生对象,使用程序实现在控制台遍历该集合
思路:
①定义学生类
②创建List集合对象
③创建学生对象
④把学生添加到集合
public class ListTest {
public static void main(String[] args) {
List<Student> arr = new ArrayList<>();
Student s1 = new Student(19, "小明");
Student s2 = new Student(21, "小黑");
Student s3 = new Student(22, "小红");
arr.add(s1);
arr.add(s2);
arr.add(s3);
//迭代器遍历
Iterator<Student> it = arr.iterator();
while(it.hasNext()) {
Student s = it.next();
System.out.println(s.getName()+","+s.getAge());
}
//普通for遍历
for(int i = 0;i<arr.size();i++) {
Student s = arr.get(i);
System.out.println(s.getName()+s.getAge());
}
//增强for遍历
for(Student s : arr) {
System.out.println(s.getName()+s.getAge());
}
}
}
public class Student {
private int age;
private String name;
public Student() {
}
public Student(int age, String name) {
super();
this.age = age;
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}