Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Hash Code

 
Karthik Vaidiswaran
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 805
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Simple. Just invoke the hashCode() method, which every object inherits from Object. It returns an int.
 
Jeroen Wenting
Ranch Hand
Posts: 5093
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Karthik Vaidiswaran
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for all the replies.It was helpful

Karthik.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic