#267 Modifying a HashMap Key After Insertion

Companies:
Simbirsoft
Themes:
JavaCollections & GenericsCode Review

What will be printed?

public class Main {

    public static void main(String[] args) {
        var usersMap = new HashMap<User, String>();

        var user1 = new User(UUID.randomUUID(), "Bruce");
        var user2 = new User(UUID.randomUUID(), "Lois");
        var user3 = new User(UUID.randomUUID(), "Ivan");
        var user4 = new User(UUID.randomUUID(), "Anna");

        var token1 = "token1";
        var token2 = "token2";
        var token3 = "token3";
        var token4 = "token4";

        usersMap.put(user1, token1);
        usersMap.put(user2, token2);
        usersMap.put(user3, token3);
        usersMap.put(user4, token4);

        user1.setName("Vasya");

        var vasyaToken = usersMap.get(user1);

        System.out.println(vasyaToken);
    }

    @AllArgsConstructor
    @Getter
    @Setter
    public static class User {
        private UUID uuid;
        private String name;

        @Override
        public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((uuid == null) ? 0 : uuid.hashCode());
            result = prime * result + ((name == null) ? 0 : name.hashCode());
            return result;
        }

        @Override
        public boolean equals(Object obj) {
            if (this == obj) {
                return true;
            }

            if (!(obj instanceof User)) {
                return false;
            }

            User other = (User) obj;

            if (uuid == null) {
                if (other.uuid != null) {
                    return false;
                }
            } else if (!uuid.equals(other.uuid)) {
                return false;
            }

            if (name == null) {
                if (other.name != null) {
                    return false;
                }
            } else if (!name.equals(other.name)) {
                return false;
            }

            return true;
        }
    }
}

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