import java.util.HashMap;
import java.util.Map;
public class HashMapTest {
public static void main(String[] args) {
HashMap<Student, String> studentMap = new HashMap<>();
// 添加多个元素
Student s1 = new Student("张三", 20);
Student s2 = new Student("李四", 22);
Student s3 = new Student("张三", 20);
//把学生添加到集合
studentMap.put(s1, "茂名");
studentMap.put(s2, "广州");
studentMap.put(s3, "湛江");
// 遍历HashMap
for (Map.Entry<Student, String> entry : studentMap.entrySet()) {
System.out.println("学生:" + entry.getKey() + ",居住地:" + entry.getValue());
}
}
}
class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
// 重写equals()方法
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
if (age != student.age) return false;
return name != null ? name.equals(student.name) : student.name == null; }
// 重写hashCode()方法
@Override
public int hashCode() {
int result = name != null ? name.hashCode() : 0;
result = 31 * result + age;
return result;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
//在上述代码中,
//我们定义了一个Student类,并在Main类中创建了一个HashMap对象来存储学生对象和居住地的对应关系。
//通过重写equals()和hashCode()方法,我们可以确保如果两个学生对象的成员变量值相同,
//它们将被视为同一个对象。
//最后,我们使用entrySet()方法来遍历HashMap集合中的元素,
//并打印出每个学生对象及其对应的居住地。