当给HashMap中存放自定义对象时,如果自定义对象作为key存在,这时要保证对象唯一,必须复写对象的hashCode和equals方法(如果忘记,请回顾HashSet存放自定义对象)。
package MONA.demo01;
import java.util.HashMap;
import java.util.Objects;
/**
* 自定义对象作为Kkey
* 当自定义对象作为key时,自定义对象必须重写一下两个方法
* hashCode
* equals
*/
public class Demo04 {
public static void main(String[] args) {
//key是唯一的
//HashMap所有的数据结构针对的都是key
HashMap<Student,String> hashMap = new HashMap<>();
hashMap.put(new Student("李四",19),"aaa");
hashMap.put(new Student("王五",20),"bbb");
hashMap.put(new Student("赵六",21),"ccc");
hashMap.put(new Student("赵六",21),"ccc");
System.out.println("hashMap"+hashMap);
}
}
class Student{
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return age == student.age &&
Objects.equals(name, student.name);
}
@Override
public int hashCode() {
return Objects.hash(name, age);
}
}