• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Fei Ng
Ranch Hand
Posts: 1245
1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
Paulo Silveira
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic