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.

Fictious mutable key
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);
    }
}

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.
Program output
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.

Morale of the story:

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

Buy my ebook for complete question bank

Most of these questions has been answered in my eBook "Cracking the Core Java Interview" updated on June 2018, that you can buy from this link:

Buy from Shunya (DRM Free PDF download with updates)

Top articles in this category:
  1. Difference between HashMap, LinkedHashMap and TreeMap
  2. Discuss internals of a ConcurrentHashmap (CHM) in Java
  3. What is difference between HashMap and HashSet
  4. Difference between HashMap and ConcurrentHashMap
  5. What is Immutable Class in Java
  6. What will happen if we don't synchronize getters/accessors of a shared mutable object in multi-threaded applications
  7. can we write a java method that swaps two integers

Recommended books for interview preparation:

Find more on this topic:
Buy interview books

Java & Microservices interview refresher for experienced developers.