#428 Mutable Key in HashMap
What will be printed?
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
Sign in to start the dialogue
The mentor keeps the context of the current question and your previous messages.
Sign in
Available with Premium
This is just one of the solutions available with Premium. And more:
- 250+ advanced lectures
- 1300+ practice exercises
- 500+ solutions to problems from real interviews
- Personalized Java Hub certificates
- Expanded access to the AI mentor