HashMap条目已丢失

时间:2018-01-30 18:37:07

标签: java hashmap hashcode containskey

我不明白为什么这段代码:

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评估为假的情况下会发生什么?

0 个答案:

没有答案