Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

hashCode and equals

 
Sherman Hung
Greenhorn
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why the following statements are false?
1. If the reference x and y denote two different objects, then the expression x.equals(y) is false.
2. If the reference x and y denote two different objects, then the expression (x.hashCoce() == y.hashCode()) is false.
 
Brian Glodde
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
1. They are 2 different objects, therefore 2 different references. Not equal. From the JavaDocs equals() definition: "Indicates whether some other object is *equal to* this one."
2. It is true the hashCode() values are different.
Code:
 
Joshua Kueck
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If reference x and y are of type Object, then x.equals(y) is equivalent to x==y. This will compare the references. However, if reference x and y are of some type that Overrides equals (most do), then it usually compares the actual objects to one another.
 
Joshua Kueck
Ranch Hand
Posts: 71
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
andy lau
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
does the hashCoce() return an object referance???
 
Brian Glodde
Ranch Hand
Posts: 171
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Andy, Try compiling the code example I posted, it'll write out the hashCode(). Also, the JavaDocs are a good source of this type of information. In short, hashCode() does just what it says, returns a hash value for the object for use in data structures such as a hashtable.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic