selvam
selvam

Reputation: 583

difference between Object reference and Object hash code

whats the difference between an Object's reference and the same object's hash code value in java ?

Upvotes: 5

Views: 10152

Answers (3)

rkg
rkg

Reputation: 5719

They are completely two 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 hashcodes will be equal.

But oldCat and newCat do not refer to the same object. They are references to two different objects. But they might have the same hashCode based on their implementation. hashCode is simply a method in Object class which you can override.

EDIT (from PeterJ): According to the JavaSE6 Object specification, if oldCat.equals(newCat) then the hashcode of the two should be equal. It's good programming to obey by that contract

You probably want to check the answers for this question as well:

difference between hash code and reference or address of an object?

Upvotes: 10

fastcodejava
fastcodejava

Reputation: 41117

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

Upvotes: 3

cherouvim
cherouvim

Reputation: 31903

A reference to an Object is just that. A reference to an Object.

An Object's hashcode is the result of the hashCode() method which depending on implementation may be various things. The default hashCode():

is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language

Upvotes: 7

Related Questions