编写Java程序,创建学员类 Student,并添加姓名、年龄、性别等字段,创建3个ArrayList<T>对象,指定T为 Student类,每个ArrayList<T>中添加一些学员对象,再创建HashMap<K,V>对象,以年级名称为键,指定为String类型,指定value类型为ArrayList<Student>,值为存放学员的ArrayList<T>对象,然后从HashMap<K,V>对象中获取某个班级的学员信息并输出。
时间: 2024-03-06 07:50:14 浏览: 51
下面是一个简单的实现示例:
```java
import java.util.ArrayList;
import java.util.HashMap;
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;
}
public static void main(String[] args) {
ArrayList<Student> grade1 = new ArrayList<>();
grade1.add(new Student("张三", 18, "男"));
grade1.add(new Student("李四", 19, "女"));
ArrayList<Student> grade2 = new ArrayList<>();
grade2.add(new Student("王五", 20, "男"));
grade2.add(new Student("赵六", 21, "女"));
ArrayList<Student> grade3 = new ArrayList<>();
grade3.add(new Student("钱七", 22, "男"));
grade3.add(new Student("孙八", 23, "女"));
HashMap<String, ArrayList<Student>> map = new HashMap<>();
map.put("一年级", grade1);
map.put("二年级", grade2);
map.put("三年级", grade3);
ArrayList<Student> students = map.get("二年级");
for (Student student : students) {
System.out.println("姓名:" + student.getName() + ",年龄:" + student.getAge() + ",性别:" + student.getGender());
}
}
}
```
在上面的示例中,我们创建了一个`Student`类,并添加了姓名、年龄、性别等字段。然后创建了三个`ArrayList<Student>`对象,每个对象中添加了一些学员对象。接着创建了一个`HashMap<String, ArrayList<Student>>`对象,以年级名称为键,值为存放学员的`ArrayList<Student>`对象。我们将三个`ArrayList<Student>`对象添加到`HashMap`对象中,并指定相应的年级名称。最后,我们从`HashMap`对象中获取了"二年级"的学员信息,并输出了学员的姓名、年龄、性别等字段。
相关推荐
![text/x-c++](https://img-home.csdnimg.cn/images/20210720083646.png)
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)