whats the difference between an Object's reference and the same object's hash code value in java ?
Java Object hashCode() is a native method and returns the integer hash code value of the object. The general contract of hashCode() method is: Multiple invocations of hashCode() should return the same integer value, unless the object property is modified that is being used in the equals() method.
When you create an object of a class as − Student obj = new Student(); The objects are created in the heap area and, the reference obj just points out to the object of the Student class in the heap, i.e. it just holds the memory address of the object (in the heap).
An object reference is information on how to find a particular object. The object is a chunk of main memory; a reference to the object is a way to get to that chunk of memory. The variable str does not actually contain the object, but contains information about where the object is.
Often we compare hashes in Ruby to Objects in JavaScript. Although they share some similarities, the functionality of both are not the same. The similarities stem from the fact that Ruby's hash and JavaScript's object appear to look the same. Lets take a look at how each are created with their seemingly similar syntax.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With