*
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


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "x.hasCode() == y.hashCode()" Watch "x.hasCode() == y.hashCode()" New topic
Author

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,
Corey


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.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: x.hasCode() == y.hashCode()