标题 对象添加到集合
自定义4个学生对象,添加到集合,并遍历
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;
}
}
import java.util.ArrayList;
public class Demo02ArrayListStudent {
public static void main(String[] args) {
ArrayList<Student> list = new ArrayList<>();
Student s1 = new Student("赵一颖" , 20);
Student s2 = new Student("赵二颖" , 21);
Student s3 = new Student("赵三颖" , 22);
Student s4 = new Student("赵四颖" , 23);
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
for (int i = 0; i < list.size(); i++) {
Student stu = list.get(i);
System.out.println("姓名" + stu.getName() + ", 年龄: " + stu.getAge());
}
}
}