• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overriding equals()

 
Janeice DelVecchio
Saloon Keeper
Posts: 1808
12
Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From Enthuware.... com.enthuware.ets.scjp.v6.2.188
If the equals() method is overridden, the hashCode() method should also be overridden such a way that same hashCode is returned for objects that are equal.


Uhmmm.... what? Why?

I thought this is why two objects should be !=, but be equals() at the same time.
 
AmanZeeK Verma
Greenhorn
Posts: 29
Android Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The statement merely means... the retrieval of the object in Collection (HashMap say) must be from the same bucket, it was stored to....

Address would/will still be different!
 
Henry Wong
author
Marshal
Pie
Posts: 21022
78
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Janeice DelVecchio wrote:
Uhmmm.... what? Why?

I thought this is why two objects should be !=, but be equals() at the same time.


It's the way hashing works. A hashmap. hashset, etc., will first use the hash to get to a bucket, then use the equals() method to compare with the elements in the same bucket, rejecting if it is a duplicate.

If the hashcodes are different, they go to different buckets, and the equals() methods is never called. In effect, you have place two "equal" objects into a collection that doesn't allow duplicates... and of course, violated the hashcode/equals contract.

Henry

 
Janeice DelVecchio
Saloon Keeper
Posts: 1808
12
Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks!!
 
Javin Paul
Ranch Hand
Posts: 295
Eclipse IDE Firefox Browser Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Its worth noting that " if two objects are equal with equals() method there hashcode must be same. but two unequal object can have same hashcode " so if that's the case it will lead frequent collision if you use that object as key in hashMap or Hashtable and that's why objects like String and wrapper class are good HashKey because for them if two objects are unequal there hashcode also differ.
 
Sunny Bhandari
Ranch Hand
Posts: 448
Eclipse IDE Firefox Browser Tomcat Server
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
That is very frequently asked question. I think out of 15 interviews I have given, at least 10 asked this question.....
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic