现在有5个学生,请把5个学生信息通过以下三种方式分别进行存储、遍历和输出。 (1)数组实现; (2)集合转数组实现; (3)集合迭代器实现;
时间: 2023-12-14 10:38:02 浏览: 138
python 编写input()和output()函数输入,输出5个学生的数据记录(示例)
学生信息包括:姓名、年龄、性别。
首先,定义一个学生类:
```java
public class Student {
private String name;
private int age;
private String gender;
public Student(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public String getGender() {
return gender;
}
}
```
然后,创建5个实例:
```java
Student s1 = new Student("张三", 18, "男");
Student s2 = new Student("李四", 19, "女");
Student s3 = new Student("王五", 20, "男");
Student s4 = new Student("赵六", 21, "女");
Student s5 = new Student("钱七", 22, "男");
```
### 数组实现
```java
Student[] students = {s1, s2, s3, s4, s5};
// 遍历数组
for (int i = 0; i < students.length; i++) {
System.out.println(students[i].getName() + "," + students[i].getAge() + "," + students[i].getGender());
}
```
### 集合转数组实现
```java
List<Student> list = new ArrayList<>();
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);
// 转为数组
Student[] students = list.toArray(new Student[list.size()]);
// 遍历数组
for (int i = 0; i < students.length; i++) {
System.out.println(students[i].getName() + "," + students[i].getAge() + "," + students[i].getGender());
}
```
### 集合迭代器实现
```java
List<Student> list = new ArrayList<>();
list.add(s1);
list.add(s2);
list.add(s3);
list.add(s4);
list.add(s5);
// 迭代器遍历
Iterator<Student> iterator = list.iterator();
while (iterator.hasNext()) {
Student student = iterator.next();
System.out.println(student.getName() + "," + student.getAge() + "," + student.getGender());
}
```
阅读全文