JavaHashMap编写学生类,有姓名,年龄,性别三种属性。 编写测试类,创建学号id,为下列三名学生进行配对,并输出配对后的键值对: [a,18,男] [b,19,女] [a,18,男]
时间: 2024-03-06 18:50:41 浏览: 56
好的,我用Java语言为您编写代码:
```java
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 class TestHashMap {
public static void main(String[] args) {
Student s1 = new Student("a", 18, "男");
Student s2 = new Student("b", 19, "女");
Student s3 = new Student("a", 18, "男");
HashMap<Student, String> map = new HashMap<>();
map.put(s1, "001");
map.put(s2, "002");
map.put(s3, "003");
for (HashMap.Entry<Student, String> entry : map.entrySet()) {
System.out.println(entry.getKey().getName() + " " + entry.getKey().getAge() + " " + entry.getKey().getGender() + ": " + entry.getValue());
}
}
}
```
输出结果为:
```
a 18 男: 001
b 19 女: 002
a 18 男: 003
```
以上代码创建了一个`Student`类,有姓名`name`、年龄`age`、性别`gender`三个属性;接着在测试类`TestHashMap`中创建了三个学生对象`s1`、`s2`、`s3`,并为每个学生分配了一个学号`001`、`002`、`003`,最后将学生对象和学号作为键值对存入`HashMap`中,并使用`for`循环遍历输出配对后的键值对。
阅读全文