5

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

1
  • 1
    [difference between hash code and reference or address of an object? ](stackoverflow.com/questions/3700595/…) is the same, even though it was originally asked for Java ME. Commented Dec 31, 2010 at 8:12

3 Answers 3

10

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?

Sign up to request clarification or add additional context in comments.

1 Comment

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.
7

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

1 Comment

On 64-bit JVMs the references will typically use 8-bytes, the hashCode() is only 32-bits.
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.