- 案例:Collection集合存储学生对象并遍历
需求:创建一个存储学生对象的集合,存储3个学生对象,使用程序实现在控制台遍历该集合。
分析:
(1)定义学生类
(2)创建Collection集合对象
(3)创建学生对象
(4)把学生添加到集合
(5)遍历集合(迭代器方式)
完整代码:
package com.xuexi;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Demo4 {
public static void main(String[] args) {
//创建Collection集合对象
Collection<Student> c = new ArrayList<Student>();
//创建学生对象
Student s1 = new Student("Tom",5);
Student s2 = new Student("Bob",6);
Student s3 = new Student("Mia",7);
//把学生添加到集合
c.add(s1);
c.add(s2);
c.add(s3);
//遍历集合(迭代器方式)
Iterator<Student> it = c.iterator();
while (it.hasNext()){
Student s = it.next();
System.out.println(s.getName()+','+s.getAge());
}
}
}
运行结果:
Tom,5
Bob,6
Mia,7
本文展示了如何在Java中创建一个Collection集合,存储学生对象,并使用迭代器遍历显示学生姓名和年龄。通过定义学生类,创建ArrayList集合,添加学生实例,然后遍历集合打印学生信息,实现数据的简单操作。
&spm=1001.2101.3001.5002&articleId=115529920&d=1&t=3&u=6b3f998feea14e45890c87f5426f8af2)

被折叠的 条评论
为什么被折叠?



