• Post Reply Bookmark Topic Watch Topic
  • New Topic

When is hashCode() called?  RSS feed

 
Sailendra Jena
Greenhorn
Posts: 10
Hibernate Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

Can anyone tell me when hashCode() method call in Java Program? When hascode number generate in Java Program? Whether in class loading time or when we are checking for equality between two class objects?

Thanks & Regards
Sailendra Narayan Jena
 
Jesper de Jong
Java Cowboy
Sheriff
Posts: 16059
88
Android IntelliJ IDE Java Scala Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hashCode() is used by hash-based collection classes such as HashSet and HashMap. Those classes will call the hashCode() method of objects that you put into the HashSet or that you use as keys in the HashMap.

Hash codes do not have anything to do with class loading.
 
Campbell Ritchie
Marshal
Posts: 56534
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please don't use coloured text throughout; some people find certain colours difficult to read. I have changed it to black.
 
Ariel Krakowski
Greenhorn
Posts: 5
Chrome Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Java uses equals to check if two Objects are equal, not hashCode. Its just important that if two Objects are equal, they should return the same hashCode. (So if you over-ride one method, you should over-ride the other method.)
 
Paweł Baczyński
Bartender
Posts: 2083
44
Firefox Browser IntelliJ IDE Java Linux Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ariel Krakowski wrote:Java uses equals to check if two Objects are equal, not hashCode. Its just important that of two Objects are equal, they should return the same hashCode and vise versa.

Not true! Two objects that are not equal might have the same hashCode.
A quote from Object#hashCode() javadoc
javadoc wrote:It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hash tables.
 
Ariel Krakowski
Greenhorn
Posts: 5
Chrome Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Updated.
 
Campbell Ritchie
Marshal
Posts: 56534
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ariel Krakowski wrote:Updated.
No, please don't update posts like that. It makes the responses look like nonsense.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!