package com.anli;
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;
}
}
package com.anli;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class Demo {
public static void main(String[] args) {
List<Student> list = new ArrayList<>();
Student s1 = new Student("1", 21);
Student s2 = new Student("2", 22);
Student s3 = new Student("3", 23);
list.add(s1);
list.add(s2);
list.add(s3);
//集合遍历
//①迭代器方式遍历
Iterator<Student> it = list.iterator();
while (it.hasNext()) {
Student ss = it.next();
System.out.println(ss.getName() + "," + ss.getAge());
}
//②普通for带索引遍历
for (int i = 0; i < list.size(); i++) {
Student sss = list.get(i);
System.out.println(sss.getName() + "," + sss.getAge());
}
//增强for
for (Student stu : list) {
System.out.println(stu.getName() + "," + stu.getAge());
}
}
}