import java.util.ArrayList;
/**
* 题目要求:自定义4个学生对象,添加到集合并遍历输出
*/
public class ArrayListTest {
public static void main(String[] args) {
// 创建4个学生对象
Student[] stu = new Student[4];
stu[0] = new Student("Bob", 18);
stu[1] = new Student("Amy", 17);
stu[2] = new Student("Tom", 19);
stu[3] = new Student();
stu[3].setName("Tim");
stu[3].setAge(18);
ArrayList<Student> list = new ArrayList<>();
// 将学生对象放入集合
for (Student x : stu) {
list.add(x);
}
// 遍历集合并输出
for (int i = 0; i < list.size(); i++) {
Student s = list.get(i);
System.out.print("姓名:" + s.getName() + " ");
System.out.print("年龄:" + s.getAge());
System.out.println();
}
ArrayList练习二:自定义4个学生对象,添加到集合并遍历输出
最新推荐文章于 2024-05-24 17:21:30 发布
本文通过实例讲述了如何在Java中使用ArrayList创建并管理自定义的学生对象集合,详细步骤包括定义学生类,初始化ArrayList,添加学生对象,以及遍历输出所有学生信息。
摘要由CSDN通过智能技术生成