Difference between object reference and object hash code

What is the difference between an Object reference and the same value of an object hash code in java?

+4
source share
3 answers

These are completely different concepts.

Cat oldCat = new Cat(); Cat newCat = new Cat(); Cat oldCatRef = oldCat; 

In the above example, oldCat and oldCatRef are references to the same object. Since they refer to the same object, their hash codes will be equal.

But oldCat and newCat do not refer to the same object. These are links to two different objects. But they can have the same hashCode based on their implementation. hashCode is just a method in the Object class that you can override.

EDIT (from PeterJ): According to the specification of the JavaSE6 object, if oldCat.equals (newCat), then the hash code of the two should be equal. This is good programming to obey this contract.

You probably also want to check the answers to this question:

difference between hash code and object link or address?

+6
source

Linking to an object is easy. Link to the object.

The hash code of the object is the result of the hashCode() method, which, depending on the implementation, may be different. By default hashCode() :

usually implemented by converting the internal address of an object to an integer, but this implementation method is not required by the JavaTM programming language

+7
source

Two different objects can have the same hashCode . A reference is a unique pointer to an object, where hashCode is a convenient computed attribute.

+3
source

Source: https://habr.com/ru/post/1333877/


All Articles