Can the keys in HashMap be mutable

Carvia Tech | May 05, 2019 | 2 min read | 177 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 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. What is Immutable Class. Why would you choose it? How would you make a class immutable?
  2. Difference between HashMap and ConcurrentHashMap
  3. Discuss internals of a ConcurrentHashmap (CHM) in Java
  4. What will happen if we don't synchronize getters/accessors of a shared mutable object in multi-threaded applications
  5. What is difference between HashMap and HashSet
  6. What is volatile keyword in Java
  7. How will you calculate factorial of a large number in Java



Find more on this topic:
Core Java image
Core Java

Core Java - OOP Concepts, Garbage Collection, Multi-threading, Collections Framework, Java 8 Features, Lambda Functions, Streams.

Last updated 1 month ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info