ArrayList练习二:自定义4个学生对象,添加到集合并遍历输出

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();
        }

    }
}

// 创建学生类
class Student {
    private String name;
    private int age;

    public Student() {

    }

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }
}

输出:

姓名:Bob    年龄:18
姓名:Amy    年龄:17
姓名:Tom    年龄:19
姓名:Tim    年龄:18

 

©️2020 CSDN 皮肤主题: 数字20 设计师:CSDN官方博客 返回首页