#428 Mutable Key in HashMap

Companies:
Iteco
Themes:
JavaCollections & GenericsCode Review

What will be printed?

Java
public class Main {
    public static void main(String[] args) {
        Map<Key, String> map = new HashMap<>();
        Key key = new Key();
        key.setKey("K1");
        map.put(key, "val1");
        key.setKey("K2");

        System.out.println(map.get(key)); // What will the code print?
    }

    static class Key {
        private String key;
        public void setKey(String key) {
            this.key = key;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Key key1 = (Key) o;
            return Objects.equals(key, key1.key);
        }

        @Override
        public int hashCode() {
            return Objects.hash(key);
        }
    }
}

Question review

Mentor
Answer as you would in a real interview. I’ll ask follow-up questions, then compare your answer with the reference answer and show your accuracy as a %.
Sign in to start the dialogue The mentor keeps the context of the current question and your previous messages.
Sign in