k13i
k13i

Reputation: 4351

HashMap entry has been lost

I don't understand why this code:

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);
        }

    }
}

prints false false. When I put Person object in a map, hash should be calculated. Then key's property is changed. While invoking containsKey, hashes should be compared and new Person("person2") has the same hash as previously inserted key. What happens that in both cases containsKey evaluates to false?

Upvotes: 0

Views: 201

Answers (0)

Related Questions