基础练习|JAVA 07-2 对象添加到集合 自定义4个学生对象,添加到集合,并遍历

标题 对象添加到集合 自定义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> 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()); } } }

    推荐阅读