用java定义一个Map<String,Student> map=New HashMap<String,Student>();,然后向map中放入2个学生,<"s1",new Student("王五","男",23)>、<"s2",new Student("王六","男",24)> 遍历map中的key和value,并将每个学生的姓名、性别、年龄输出到显示器。
时间: 2023-07-19 18:21:41 浏览: 77
好的,我可以帮您解决这个问题。以下是示例代码:
```java
import java.util.*;
public class Main {
public static void main(String[] args) {
Map<String, Student> map = new HashMap<String, Student>();
map.put("s1", new Student("王五", "男", 23));
map.put("s2", new Student("王六", "男", 24));
for (String key : map.keySet()) {
System.out.println("key: " + key);
Student student = map.get(key);
System.out.println("姓名: " + student.getName() + " 性别: " + student.getGender() + " 年龄: " + student.getAge());
}
}
}
class Student {
private String name;
private String gender;
private int age;
public Student(String name, String gender, int age) {
this.name = name;
this.gender = gender;
this.age = age;
}
public String getName() {
return name;
}
public String getGender() {
return gender;
}
public int getAge() {
return age;
}
}
```
运行结果如下:
```
key: s1
姓名: 王五 性别: 男 年龄: 23
key: s2
姓名: 王六 性别: 男 年龄: 24
```
以上就是示例代码和输出结果,希望能够帮到您。
阅读全文