File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes x.hasCode() == y.hashCode() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "x.hasCode() == y.hashCode()" Watch "x.hasCode() == y.hashCode()" New topic

x.hasCode() == y.hashCode()

Fei Ng
Ranch Hand

Joined: Aug 26, 2000
Posts: 1242
If the references x and y denote two different objects then the expression (x.hashCode() == y.hashCode()) is always false.

True or false? explain.
Paulo Silveira
Ranch Hand

Joined: May 21, 2002
Posts: 32
false, not always
the hashCode is simply a number calculated for storing the object in a hash properly.
you can also prove this way
supose you do have 2^64 +1 objects, at least two of them must have identicals hashcodes, because there is not enough numbers for each object hashcode.
Corey McGlone
Ranch Hand

Joined: Dec 20, 2001
Posts: 3271
One example of how this can be false comes from the String class. In the String class, the hash code is derived from the contents of the String. Try running the following code:

So, in this case, even though we've created two distinct objects, they have the same hash code.
I hope that helps,

SCJP Tipline, etc.
Paulo Silveira
Ranch Hand

Joined: May 21, 2002
Posts: 32
the rule is
if x.equals(y), the x.hashCode() == y.hashCode()
if your class does not repect this, you will get some problems when using some Util classes and so on.
I agree. Here's the link:
subject: x.hasCode() == y.hashCode()
It's not a secret anymore!