分别用ArrayList,HashSet,HashMap存储5个学生对象并遍历
时间: 2024-02-01 21:14:39 浏览: 83
首先,我们需要定义一个学生类,如下所示:
```java
public class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
```
接下来,我们可以使用 ArrayList、HashSet 和 HashMap 来存储 5 个学生对象,并遍历它们。
使用 ArrayList 存储 5 个学生对象:
```java
List<Student> students = new ArrayList<>();
students.add(new Student("Tom", 18));
students.add(new Student("Jerry", 20));
students.add(new Student("Alice", 19));
students.add(new Student("Bob", 21));
students.add(new Student("David", 22));
for (Student student : students) {
System.out.println("Name: " + student.getName() + ", Age: " + student.getAge());
}
```
使用 HashSet 存储 5 个学生对象:
```java
Set<Student> students = new HashSet<>();
students.add(new Student("Tom", 18));
students.add(new Student("Jerry", 20));
students.add(new Student("Alice", 19));
students.add(new Student("Bob", 21));
students.add(new Student("David", 22));
for (Student student : students) {
System.out.println("Name: " + student.getName() + ", Age: " + student.getAge());
}
```
使用 HashMap 存储 5 个学生对象:
```java
Map<String, Student> students = new HashMap<>();
students.put("Tom", new Student("Tom", 18));
students.put("Jerry", new Student("Jerry", 20));
students.put("Alice", new Student("Alice", 19));
students.put("Bob", new Student("Bob", 21));
students.put("David", new Student("David", 22));
for (String key : students.keySet()) {
Student student = students.get(key);
System.out.println("Name: " + student.getName() + ", Age: " + student.getAge());
}
```
注意,使用 HashMap 存储时,我们需要指定一个键值对。在上面的例子中,我们将学生的名字作为 key,学生对象作为 value 存储到 HashMap 中。在遍历时,我们需要先获取所有的 key,然后通过 key 获取对应的 value。
阅读全文