Java Interview Question

Use this advanced question and answer to prepare for your next Java interview.

Does a HashMap Key object have to be Immutable?

HashMap calculates the location of an object based on the value of the hashCode function. If the values used to calculate the hashCode of an object change after it is inserted in the HashMap, this will result in the Key returning a different address than the one originally used. In this case, the HashMap cannot locate the original Key and the object is lost in the Map, indicating that the Key does not exist.

This is not a compiler or runtime requirement by the HashMap class, but, due to the problems it can create, it is an expectation from any good developer to look out for this.

Looking for developers?