我不明白为什么这段代码:
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
public class Main {
public static void main(String[] args) {
Map<Person, String> map = new HashMap<>();
Person person = new Person("person");
map.put(person, "");
person.name = "person2"; // key's property changed
System.out.println(map.containsKey(new Person("person")));
System.out.println(map.containsKey(new Person("person2")));
}
static class Person {
String name;
Person(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return Objects.equals(name, person.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
}
}
打印false
false
。当我将Person
对象放入地图时,应计算哈希值。然后键的属性被更改。在调用containsKey
时,应比较哈希值,new Person("person2")
具有与先前插入的键相同的哈希值。在containsKey
评估为假的情况下会发生什么?