开发者

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 ?


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?


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜