集合 案例:存储学生对象并遍历

案例:存储学生对象并遍历

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

思路:

1. 定义学生类

2. 创建集合对象

3. 创建学生对象

4 .添加学生对象到集合

5. 遍历集合,采用通用遍历格式实现

代码示例:

import java.util.ArrayList;

/*
        1. 定义学生类

2. 创建集合对象

3. 创建学生对象

4 .添加学生对象到集合

5. 遍历集合,采用通用遍历格式实现
 */
public class ArrayListDemo03 {
    public static void main(String[] args) {
//        创建集合对象
        ArrayList<Student> array= new ArrayList<Student>();
        // 创建学生对象
        Student s1= new Student("张三",30);
        Student s2= new Student("李四",34);
        Student s3= new Student("王五",36);
        //添加对象到集合中
        array.add(s1);
        array.add(s2);
        array.add(s3);
        //遍历集合
        for(int i = 0;i< array.size();i++){
            Student s = array.get(i);
            System.out.println(s.getName()+","+s.getAge());

        }


    }
}

学生类:

/*
         学生类

 */
public 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;
    }
}

猜你喜欢

转载自blog.csdn.net/m0_68089732/article/details/124238208