构造Student类,该类包含学号、姓名。利用ArrayList构造集合,该集合中存储40个Student对象,要求学号实现从1开始递增(即40个Student对象的学号是1到40),利用foreach和iterator这两种方式对集合进行遍历
时间: 2024-12-28 08:41:15 浏览: 7
首先,我们创建一个`Student`类,包含学号和姓名两个属性:
```java
public class Student {
private int studentId;
private String name;
public Student(int id, String name) {
this.studentId = id;
this.name = name;
}
// getters and setters
public int getStudentId() { return studentId; }
public void setStudentId(int studentId) { this.studentId = studentId; }
public String getName() { return name; }
public void setName(String name) { this.name = name; }
}
```
接着,我们可以创建一个ArrayList来存储40个Student对象,同时初始化学号:
```java
List<Student> students = new ArrayList<>();
Random random = new Random();
for (int i = 1; i <= 40; i++) {
students.add(new Student(i, "学生" + i)); // 学号从1开始递增
}
```
现在我们分别通过`foreach`和`iterator`两种方式进行遍历:
**使用foreach循环遍历:**
```java
System.out.println("Using foreach loop:");
for (Student student : students) {
System.out.printf("学生ID: %d, 姓名: %s%n", student.getStudentId(), student.getName());
}
```
**使用迭代器遍历:**
```java
System.out.println("Using iterator:");
Iterator<Student> iterator = students.iterator();
while (iterator.hasNext()) {
Student student = iterator.next();
System.out.printf("学生ID: %d, 姓名: %s%n", student.getStudentId(), student.getName());
}
```
以上代码会打印出每个学生的学号和姓名,遍历顺序相同,都是按添加的顺序(即1到40)。
阅读全文