(1)利用Arraylist实现类创建一个List集合,存储三个用户输入的学生对象。 学生类的属性:姓名,年龄。 (2)分别用普通的for 循环、增强for 循环、lterator迭代器三种遍历方式遍
时间: 2024-10-26 18:02:29 浏览: 15
Java动态获取实现某个接口下所有的实现类对象集合
(1)首先,我们需要创建一个`Student`类,包含姓名和年龄两个属性:
```java
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
// getters and setters...
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
```
接下来,我们可以使用ArrayList创建一个List集合并添加三个学生对象:
```java
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
ArrayList<Student> studentList = new ArrayList<>();
Scanner scanner = new Scanner(System.in);
System.out.println("请输入第一个学生的姓名和年龄:");
String name1 = scanner.nextLine();
int age1 = scanner.nextInt();
Student student1 = new Student(name1, age1);
studentList.add(student1);
System.out.println("请输入第二个学生的姓名和年龄:");
String name2 = scanner.nextLine();
int age2 = scanner.nextInt();
Student student2 = new Student(name2, age2);
studentList.add(student2);
System.out.println("请输入第三个学生的姓名和年龄:");
String name3 = scanner.nextLine();
int age3 = scanner.nextInt();
Student student3 = new Student(name3, age3);
studentList.add(student3);
// ... 然后使用下面的方法遍历列表
}
}
```
(2)遍历`studentList`的三种方式:
- 普通for循环:
```java
for (int i = 0; i < studentList.size(); i++) {
Student student = studentList.get(i);
System.out.println(student.toString());
}
```
- 增强for循环(也称为foreach循环):
```java
for (Student student : studentList) {
System.out.println(student.toString());
}
```
- 使用Iterator迭代器:
```java
Iterator<Student> iterator = studentList.iterator();
while (iterator.hasNext()) {
Student student = iterator.next();
System.out.println(student.toString());
}
```
阅读全文