• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt regarding equals() and hashCode()

 
Nitin Kumar
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the chapter 'Collection's in K&B book, it is written many a times that

statement 1 " if x.equals(y) is true, then x.hashCode() == y.hashCode() "

and

Statement 2 "If you override equals() then override hashCode() ;

But the following code, which is also from K&B book, page 546, runs fine even though hashCode() method doesn't return same value and is not overwritten




this code gives output of " One and two are equal ". Two things that are confusing for me are :
a) Even if the hashCode() is not overwritten then how come two instances ( one and two) are equal ( seems to violate statement 2 )
b) Two instances are equal but one.hashCode() and two.hashCode() are not equal. ( seems to violate statement 1 )

After doing some more search I came to the conclusion that the above statements, are ONLY valid if the concerned classes are used in Collection Framework, i,e in Maps,Sets, Lists and Queues.

Could you please let me know if the above conclusion is correct or I am missing something.

Thanks


 
Ankit Garg
Sheriff
Posts: 9519
22
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
After doing some more search I came to the conclusion that the above statements, are ONLY valid if the concerned classes are used in Collection Framework, i,e in Maps,Sets, Lists and Queues.

Yes you are right, if you break the equals-hashCode contract (i.e. for equal objects hashCode is different etc), then the objects might not work correctly with collections (more specifically hash based collections like HashSet, HashMap etc) because they need the hashCode and equals method to identify elements correctly for retrieval from the collection...
 
Nitin Kumar
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ankit,

Thanks for the confirmation ...
 
saima kanwal
Ranch Hand
Posts: 148
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does it mean that when we write a class in which we break the contract for hashcode and equals , our code will still compile and run??
 
Wouter Oet
Saloon Keeper
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why don't you try it?
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic