| Author |
Hash Code
|
Karthik Vaidiswaran
Greenhorn
Joined: Jan 11, 2005
Posts: 16
|
|
Please give me information about the way of finding the hashcode of an object. I have heard that hashcode of an object is the address of memory location of the object. How do I find the hashcode? Thanks Karthik.
|
 |
Jeff Bosch
Ranch Hand
Joined: Jul 30, 2003
Posts: 804
|
|
|
Simple. Just invoke the hashCode() method, which every object inherits from Object. It returns an int.
|
Give a man a fish, he'll eat for one day. <br />Teach a man to fish, he'll drink all your beer.<br /> <br />Cheers,<br /> <br />Jeff (SCJP 1.4, SCJD in progress, if you can call that progress...)
|
 |
Jeroen Wenting
Ranch Hand
Joined: Oct 12, 2000
Posts: 5093
|
|
the hashcode is NOT the address in memory of an object instance. In fact, that would yield a hashcode which is by definition incorrect as it doesn't confirm to the hashcode definition which states explicitly that two identical objects MUST have the same hashcode. As no two objects (whether identical or not) can exist in the same place in memory at the same time that's an impossibility if you take the object's memory address as the hashcode.
|
42
|
 |
Jim Yingst
Wanderer
Sheriff
Joined: Jan 30, 2000
Posts: 18670
|
|
|
Well, the hashcode may be equal to (or directly derived from) the memory address, if we're talking about the implementation defined inside the Object class. But many classes override this definition of equals(), and thus they must also override hashCode() too for consistency. So in general the hashCode is probably not based on memory location, but in some cases it may be.
|
"I'm not back." - Bill Harding, Twister
|
 |
Mike Gershman
Ranch Hand
Joined: Mar 13, 2004
Posts: 1272
|
|
the hashcode definition which states explicitly that two identical objects MUST have the same hashcode.
The rule is that two objects where equals() is true must have the same hashcode. If we use the default Object.equals() method, only the same object will have equals() true. In that case, the memory address will be the same.
|
Mike Gershman
SCJP 1.4, SCWCD in process
|
 |
Karthik Vaidiswaran
Greenhorn
Joined: Jan 11, 2005
Posts: 16
|
|
Thanks for all the replies.It was helpful Karthik.
|
 |
 |
|
|
subject: Hash Code
|
|
|