创建一个HashMap集合,用于存储学生对象,其中键是学生对象,值是学生所属专业(存入元素后使用键值对遍历)Java代码实现
时间: 2023-12-15 17:05:36 浏览: 111
```java
import java.util.HashMap;
import java.util.Map;
public class Student {
private String name;
private String major;
public Student(String name, String major) {
this.name = name;
this.major = major;
}
public String getName() {
return name;
}
public String getMajor() {
return major;
}
public static void main(String[] args) {
Map<Student, String> studentMap = new HashMap<>();
Student student1 = new Student("Alice", "Computer Science");
Student student2 = new Student("Bob", "Mathematics");
Student student3 = new Student("Charlie", "Biology");
studentMap.put(student1, student1.getMajor());
studentMap.put(student2, student2.getMajor());
studentMap.put(student3, student3.getMajor());
for (Map.Entry<Student, String> entry : studentMap.entrySet()) {
System.out.println(entry.getKey().getName() + " belongs to " + entry.getValue());
}
}
}
```
输出结果为:
```
Alice belongs to Computer Science
Charlie belongs to Biology
Bob belongs to Mathematics
```
阅读全文