Java教程

JavaSE-14.2.2【案例-List集合存储学生对象并遍历】

本文主要是介绍JavaSE-14.2.2【案例-List集合存储学生对象并遍历】,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
package day5.lesson2;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/*
2.3 案例-List集合存储学生对象并遍历
    创建一个存储学生对象的集合,存储3个学生对象,使用程序实现在控制台遍历该集合
 */
public class ListDemo2 {
    public static void main(String[] args) {
        List<Student> list = new ArrayList<>();

        Student s1 = new Student("sam", 12);
        Student s2 = new Student("amy", 11);
        Student s3 = new Student("tom", 12);

        list.add(s1);
        list.add(s2);
        list.add(s3);

        //遍历方式1
        Iterator<Student> it = list.iterator();
        while (it.hasNext()){
            Student s = it.next();
            System.out.println(s.getName() + "," + s.getAge());
        }

        //遍历方式2
        for(int i=0; i<list.size(); i++){
            Student stu = list.get(i);
            System.out.println(stu.getName() + "," + stu.getAge());
        }

    }
}

  

package day5.lesson2;

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 void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public int getAge() {
        return age;
    }
}

  

这篇关于JavaSE-14.2.2【案例-List集合存储学生对象并遍历】的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!