Yes. We can use any class as a Map key, however the following points should be considered before using them.
If a class overrides an equals() method, it should also overrides hashCode() method.
Best practice for user defined key class is to make immutable, so that the hashcode value can be cached for fast performance. Also immutable classes make sure that hashCode() and equals() will not change in future that will solve any issues with mutability.
For an example, let’s say I have a class that I’m using for the HashMap key.
//Avengers name argument passed is used for equals() and hashCode()
Avengers fictionKey = new Avengers(); //assume hasCode is 1234
myHashMap.put(fictionKey, "IronMan");
// Below code will change the key hashCode() and equals()
// but its location is not changed
fictionKey.setName("Stark"); //assume new hashCode is 4321
//below will return null because HashMap will try to look for key
//in the same index as it was stored but since the key is mutated,
//there will be no match and it will return null
myHashMap.get(new Avengers("IronMan"));
The reason why String and Integers are mostly used in HashMap keys.







Leave a comment