Unequal objects must have different hash codes –
Objects with the same hash code must be equal –
An object’s () method must take the same fields into account as its method.
By overriding the method, you’re declaring some objects as equal to other objects, but the original method treats all objects as different (JVM create default hash code using the object memory address). So you will have with different hash codes.
For example, calling on a will return , even though the object has been added.
is nothing critical, it just means that there is more than one object in a single bucket, so a HashMap lookup has to look again to find the right object.
For example: the Strings and produce the same hashCode: .
HashCodes can change
Important and surprising for contract: does not guarantee the same result in different executions.
For these classes like String, the hash code will always be the same because of their exact formula.
There are Java libraries that actually return different values in different processes and this tends to confuse people.
Example: Google’s Protocol Buffers.
A remote object may have a different hash code than a local one, even if the two are equal. Therefore, you should not use the hash code in distributed applications.
We must aware that the implementation of a may change from one version to another. Therefore your code should not depend on any particular hash code values.
Example: We should not use the hash code to persist state. Because the hashCode method implementation may change next time, the hash codes of the “same” objects may be different due to version change.
“D, except when you create hash-based algorithms.