class MutableKey {
private String name;
public void setName(String name) {
this.name = name;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
MutableKey that = (MutableKey) o;
return name.equals(that.name);
}
@Override
public int hashCode() {
return Objects.hash(name);
}
}
Can the keys in HashMap be mutable
Upasana | August 03, 2019 | 2 min read | 1,956 views | Multithreading and Concurrency
Interviewer’s intent is to judge your knowledge about Hashing Data Structure. |
The answer is NO. Making keys in any hashing data structure will cause memory leak.
If we make the keys mutable then the hashcode()
of the key will no more be consistent over time which will cause lookup failure for that object from the data structure.
Let’s analyze this example.
Lets create a HashMap that uses this MutableKey as the key, as shown in following code.
public class MutableKeyTest {
@Test
public void testMutableKey(){
Map testMap = new HashMap<MutableKey, Object>();
MutableKey mutableKey = new MutableKey();
mutableKey.setName("TestName");
testMap.put(mutableKey, new Object());
Object o = testMap.get(mutableKey);
System.out.println("before changing key = " + o);
mutableKey.setName("NewName"); (1)
o = testMap.get(mutableKey);
System.out.println("after changing key = " + o);
}
}
1 | We are altering the key, so its hashcode will also change. |
before changing key = java.lang.Object@5479e3f
after changing key = null
From the above example we see that as soon as we change the key, we are not able to get the associated object from the Map.
Why did that happen?
When we put the mutableKey to HashMap
then hashcode()
is calculated for the key, suppose it comes out to be 11. So the Object123 is successfully inserted into the HashMap at bucket Location 11.
Then we modify the key and try to get the object.
HashMap’s get() method again calculates the hashcode of the Key, since the Key is changed in between, so suppose hashcode() comes out to be 33 this time. Now the get() method goes to the bucket at address 33 and tries to retrieve the object, but it find nothing over there and returns the null.
Never make changes to the hashmap’s key, otherwise the associated object can not be fetched using get() method. Though it will be accessible using other methods which iterate over the entire collection.
Key of hashmap shall always be an immutable class, like String
|
Top articles in this category:
- Difference between HashMap, LinkedHashMap and TreeMap
- Discuss internals of a ConcurrentHashmap (CHM) in Java
- What is difference between HashMap and HashSet
- Difference between HashMap and ConcurrentHashMap
- What is Immutable Class in Java
- What will happen if we don't synchronize getters/accessors of a shared mutable object in multi-threaded applications
- can we write a java method that swaps two integers