编写代码,并写出运行结果。需求:创建一个Collection集合存储学生对象的集合,存储3个学生对象,使用程序实现在控制台遍历该集合。思路: 1.定义学生类 2.创建Collection集合对象 3.创建学生对象 4.把学生添加到集合 5.遍历集合(迭代器方式)
时间: 2024-05-01 17:21:52 浏览: 88
以下是实现你所需求的代码,运行结果也附在下面:
```java
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
public class Student {
private int id;
private String name;
private int age;
public Student(int id, String name, int age) {
this.id = id;
this.name = name;
this.age = age;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public static void main(String[] args) {
Collection<Student> students = new ArrayList<Student>();
Student student1 = new Student(1, "Tom", 18);
Student student2 = new Student(2, "Jerry", 19);
Student student3 = new Student(3, "Mike", 20);
students.add(student1);
students.add(student2);
students.add(student3);
Iterator<Student> it = students.iterator();
while (it.hasNext()) {
Student student = it.next();
System.out.println("id:" + student.getId() + " name:" + student.getName() + " age:" + student.getAge());
}
}
}
```
运行结果:
```
id:1 name:Tom age:18
id:2 name:Jerry age:19
id:3 name:Mike age:20
```
阅读全文