• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

equals() and hashCode()

 
Urs Waefler
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I do not understand why the behavior is different.

 
Paul Clapham
Sheriff
Pie
Posts: 20971
31
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What behaviour is that? And what is it different from, and in what way?
 
Urs Waefler
Ranch Hand
Posts: 77
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Firstly you get:
null
2

Secondly you get:
Y
1

Obviously the first output is false. The only difference is, that you do not override the method hashCode().
 
Paul Clapham
Sheriff
Pie
Posts: 20971
31
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Which explains what it says in the API documentation for Object:
If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result.

Since you are implicitly using the hashCode method by putting your objects into a HashMap, you should follow this rule. And since you are getting unexpected results, perhaps you didn't follow this rule. That would mean that you have created two objects which are "equal" but have different hashCode values; you could check that with a little debugging.

And your second (correct) example has a hashCode method which does follow that rule, and so you get correct-looking results.
 
Rob Spoor
Sheriff
Pie
Posts: 20512
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
HashSet, HashMap etc first use the return value of hashCode() to find the "bucket" the object is in. After that it uses equals to check all elements inside the bucket. If hashCode() does not follow the contract then the HashSet / HashMap will look in the wrong bucket.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic