A mutable key or object means that you can modify the object [by modify i mean you can change values represented by object]. This will impact its storage in HashMap
if the logic written in equals and hashcode uses these modifiable value.
Immutability ideally means that object once initialized cannot be changed after that. But if we talk specifically in terms of HashMap
then all the variables which are used inside equals and hashcode method, if they can be modified then that object should not be used as key else it can be used as key [but still not recommended].
Its not just about String
, any about would cache its hashcode. Hashcode is generated again and again for almost all objects [There is a reason why i say almost as in some cases it can change]. Hashcode is cached in Object header.
If you want to use mutable object as key then you should go for IdentityHashMap
. Just read about them, they can be useful in such cases.