aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Overriding equals() Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Overriding equals()" Watch "Overriding equals()" New topic
Author

Overriding equals()

Janeice DelVecchio
Saloon Keeper

Joined: Sep 14, 2009
Posts: 1726
    
  12

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.


When you do things right, people won't be sure you've done anything at all.
AmanZeeK Verma
Greenhorn

Joined: Dec 06, 2010
Posts: 29

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!


Aman ZeeK Verma
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 18997
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Janeice DelVecchio
Saloon Keeper

Joined: Sep 14, 2009
Posts: 1726
    
  12

Thanks!!
Javin Paul
Ranch Hand

Joined: Oct 15, 2010
Posts: 281


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.

http://javarevisited.blogspot.com - java classpath - Java67 - java hashmap - java logging tips java interview questions Java Enum Tutorial
Sunny Bhandari
Ranch Hand

Joined: Dec 06, 2010
Posts: 448

That is very frequently asked question. I think out of 15 interviews I have given, at least 10 asked this question.....


Java Experience
 
Don't get me started about those stupid light bulbs.
 
subject: Overriding equals()