【Java】ArrayList集合存入学生对象

需求:创建一个存储学生对象的集合,存储5个学生对象,使用程序实现在控制台遍历该集合

package com.collection.Demo02;

public class Student {
    private String userName;
    private int age;

    /**
     * 给成员属性赋值
     * 1.构造方法
     * 2.set方法
     */
    public Student(String userName, int age) {
        this.userName = userName;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "userName='" + userName + '\'' +
                ", age=" + age +
                '}';
    }

    public String getUserName() {
        return userName;
    }

    public int getAge() {
        return age;
    }
}

package com.collection.Demo02;

import java.util.ArrayList;

public class Test01 {
    public static void main(String[] args) {
        //1.创建5个学生对象
        Student s1 = new Student("name1", 20);
        Student s2 = new Student("name2", 20);
        Student s3 = new Student("name3", 20);
        Student s4 = new Student("name4", 20);
        Student s5 = new Student("name5", 20);
        //2.学生集合
        ArrayList students = new ArrayList<>();
        students.add(s1);
        students.add(s2);
        students.add(s3);
        students.add(s4);
        students.add(s5);
        System.out.println("存入5个学生对象成功");
        System.out.println("开始遍历集合中学生对象");
        //3.遍历集合中的数据
        for (Student student : students) {
            System.out.println("学生姓名:" + student.getUserName() + "  学生年龄:" + student.getAge());
//            System.out.println(student.toString());
        }
    }
}

运行结果:

【Java】ArrayList集合存入学生对象_第1张图片


优化

∵ 在创建学生对象的时候,把学生的信息写死了

∴ 改为键盘录入

package com.collection.Demo02;

import java.util.ArrayList;
import java.util.Scanner;

/**
 * 优化
 */
public class Test02 {
    public static void main(String[] args) {
        ArrayList students = new ArrayList<>();
        for (int i = 1; i <= 5; i++) {
            Scanner sc = new Scanner(System.in);
            System.out.print("请输入第" + i + "位学生姓名:");
            String userName = sc.nextLine();
            System.out.print("请输入第" + i + "位学生年龄:");
            int age = sc.nextInt();
            students.add(new Student(userName, age));
            System.out.println("======================");
        }
        for (Student student : students) {
            System.out.println("学生姓名:" + student.getUserName() + "  学生年龄:" + student.getAge());
        }
    }
}

运行结果:

【Java】ArrayList集合存入学生对象_第2张图片


下一篇文章:学生管理系统项目演示

你可能感兴趣的:(集合,java,开发语言,集合,ArrayList,集合存入学生对象)