I know that the hashmap keys should be immutable objects or at least have a consistent hashcode to properly retrieve its value from the Map/Set. But if I use a mutating object as key without overriding hashcode or equals, will its hashcode be consistent thought its life cycle. I have tried it to retrive hashcode of a mutating object and have found it consistent always.
4 Answers
The contract for hashcode states:
Whenever it is invoked on the same object more than once during an execution of a Java application, the hashCode method must consistently return the same integer, provided no information used in equals comparisons on the object is modified.
So there is no guarantee that the hashcode won't change if you mutate your object. It happens that some JDK implementations might use some sort of internal address but they don't have to so you should not rely on that.
5 Comments
return 1; is valid. You may want to search for "hashcode collision", there are several Q&A on Stackoverflow, e.g. stackoverflow.com/q/4360035/829571The default hash code of the object will not change over time in the latest version of the HotSpot JVM. In fact, the hash code is derived from the initial allocation address and entered in the object header (see JVM Whitepaper) as the object is moved by the garbage collector and will not change afterwards.
Comments
Yes, it will be constant if you don't override the hashCode method. The default hashCode is the original location of the object in memory. This memory location is retrieved by this method:
System.identityHashCode(Object)
Check out this thread on StackOverflow:
How does the JVM ensure that System.identityHashCode() will never change?