JavaSE-14.2.2案例-List集合存储学生对象并遍历
Posted yub4by
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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集合存储学生对象并遍历的主要内容,如果未能解决你的问题,请参考以下文章