The JVM, or HashMap, does not automatically cache hash codes of your keys. You have to do that yourself, in the implementation of the hashCode() method of the objects that you use as keys.
Why you would want to do that: For performance optimization; if an object is immutable, its hash code should always be the same, so you don't need to compute it every time hashCode() is called. So, it's to avoid unnecessary computations.
How it is done: You have to do it in the implementation of your hashCode() method, the JVM isn't doing this automatically for you, because the JVM doesn't know if your objects are immutable or not.
Keys in a Map
should always be immutable, but it's your job to make sure that is so - the JVM or the
Java compiler can't force you to make your key objects immutable.