请用java实现:现在有5个学生,请把5个学生信息通过以下三种方式分别进行存储、遍历和输出。 (1)数组实现; (2)集合转数组实现; (3)集合迭代器实现;
时间: 2023-12-14 22:39:34 浏览: 60
java课堂作业:用二维数组存储五个学生姓名学号,并用正则表达式判断输入数据是否有误。输出按学号排序的学生。
5星 · 资源好评率100%
好的,以下是Java代码实现:
```java
import java.util.*;
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;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
", gender='" + gender + '\'' +
'}';
}
public static void main(String[] args) {
// 通过数组实现
Student[] studentsArray = new Student[5];
studentsArray[0] = new Student("张三", 18, "男");
studentsArray[1] = new Student("李四", 19, "女");
studentsArray[2] = new Student("王五", 20, "男");
studentsArray[3] = new Student("赵六", 21, "女");
studentsArray[4] = new Student("钱七", 22, "男");
System.out.println("通过数组实现:");
for (int i = 0; i < studentsArray.length; i++) {
System.out.println(studentsArray[i]);
}
// 通过集合转数组实现
List<Student> studentsList = new ArrayList<>();
studentsList.add(new Student("张三", 18, "男"));
studentsList.add(new Student("李四", 19, "女"));
studentsList.add(new Student("王五", 20, "男"));
studentsList.add(new Student("赵六", 21, "女"));
studentsList.add(new Student("钱七", 22, "男"));
Student[] studentsArray2 = studentsList.toArray(new Student[0]);
System.out.println("通过集合转数组实现:");
for (int i = 0; i < studentsArray2.length; i++) {
System.out.println(studentsArray2[i]);
}
// 通过集合迭代器实现
List<Student> studentsList2 = new ArrayList<>();
studentsList2.add(new Student("张三", 18, "男"));
studentsList2.add(new Student("李四", 19, "女"));
studentsList2.add(new Student("王五", 20, "男"));
studentsList2.add(new Student("赵六", 21, "女"));
studentsList2.add(new Student("钱七", 22, "男"));
System.out.println("通过集合迭代器实现:");
Iterator<Student> iterator = studentsList2.iterator();
while (iterator.hasNext()) {
System.out.println(iterator.next());
}
}
}
```
输出如下:
```
通过数组实现:
Student{name='张三', age=18, gender='男'}
Student{name='李四', age=19, gender='女'}
Student{name='王五', age=20, gender='男'}
Student{name='赵六', age=21, gender='女'}
Student{name='钱七', age=22, gender='男'}
通过集合转数组实现:
Student{name='张三', age=18, gender='男'}
Student{name='李四', age=19, gender='女'}
Student{name='王五', age=20, gender='男'}
Student{name='赵六', age=21, gender='女'}
Student{name='钱七', age=22, gender='男'}
通过集合迭代器实现:
Student{name='张三', age=18, gender='男'}
Student{name='李四', age=19, gender='女'}
Student{name='王五', age=20, gender='男'}
Student{name='赵六', age=21, gender='女'}
Student{name='钱七', age=22, gender='男'}
```
阅读全文