修改了key之后不能remove
class Student implements Serializable {
Integer id;
String name;
public Student(Integer id, String name) {
this.id = id;
this.name = name;
}
public Student() {
}
//getter,setter....
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Student student = (Student) o;
return Objects.equals(getId(), student.getId()) &&
Objects.equals(getName(), student.getName());
}
@Override
public int hashCode() {
return Objects.hash(getId(), getName());
}
}
Map<Student,Integer> map=new HashMap<>(4);
Student stu1=new Student(1,"zs"),stu2=new Student(2,"ls");
map.put(stu1,1);
map.put(stu2,2);
stu1.setName("hhh");
map.remove(stu1);
for (Student student : map.keySet()) {
System.out.println(student);
}
问题的原因是对key进行了修改(因为key类重写了hashcode和equals方法,所以key对象的hash也会随之改变),由于对象在map中的位置是由修改前的key的hash计算而来的,而删除过程中的查找使用的是修改后的对象的hash,两次hash不一致,因此找不到