As I understand it equal hash codes in general imply a high probability of equality between objects, but they aren't perfect. But I've been told that in Java the base hash code of an Object is simply the memory address of the object, so I've assumed that Object hash codes are effectively perfect(two objects can't occupy the same space in memory right?). But I've been relaying very heavily on this assumption for a program I'm writing and I've started to think I should really get a definitive answer on this instead of continuing with my assumption.

6 Years
Discussion Span
Last Post by jwenting

No, it seems that it isn't safe to make such an assumption. As per this article:

the default implementation of hashCode() provided by Object is derived by mapping the memory address of the object to an integer value. Because on some architectures the address space is larger than the range of values for int, it is possible that two distinct objects could have the same hashCode()

BTW, why are you making these assumptions? Certain context regarding the actual problem might go a long way in arriving at a valid solution...


Don't use hashcode to imply equality(). You can read the hashCode() method documentation here, it explains how what you've said is not a guarantee. Besides, if you don't care about logical equality (i.e. the equals() method) and all you care about is whether or not the Objects are in the same memory location, you can just use '==' for comparison in that case.

Edit: Sorry s.o.s, posted at the same time. OP: I agree with s.o.s that you should provide some context.

Edited by BestJewSinceJC: n/a


But I've been told that in Java the base hash code of an Object is simply the memory address of the object

As has been implied already, someone told you wrong.


Given two references I want them to be equal only if they reference the same instance, so I typically use the == operator.


It is extremely simple to determine that hashcodes are not unique.
A hashcode is a 32 bit integer, it is possible to create more object instances than fit inside a 32 bit integer. Ergo, a hashcode cannot possibly be unique, as there are more possible object instances than possible hashcodes and every object instances will have a hashcode.
Even simpler reasoning is that it's possible to override hashcode with another method that returns a fixed value.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.