• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • Ron McLeod
  • paul wheaton
  • Jeanne Boyarsky
Sheriffs:
  • Paul Clapham
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
  • Himai Minh
Bartenders:

Confused about hashCode() and equals() method contracts

 
Ranch Hand
Posts: 51
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Following is a qoute from K & B SCJP 1.4 book:

".... equals() and hashCode() are bound together by a joint contract that specifies if two objects are considered equal using the equals() method, then they must have identical hashcode values..."



Following is a snippet of code from the same book which I have modified to print the hashcode values of the objects and see if the values are equal:




If you run this program, you'll find the hashcode values for the objects are different. I know I haven't overridden the hashCode() method and hence the different hashcode values in the output.

Is it only necessary to override the hashCode() method only when it is going to be used by some collection classes? And finally, can this be considered as a "correct or appropriate" implementation as it clearly violating the abovementioned contract? Thanks!
 
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Java theory and practice: Hashing it out.
 
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator


Is it only necessary to override the hashCode() method only when it is going to be used by some collection classes? And finally, can this be considered as a "correct or appropriate" implementation as it clearly violating the abovementioned contract? Thanks![/QB]



Yes it is necessary to override hashCode() for proper use of collections which depend on hash keys

I would say bove example is not appropriate ,however it is legal in java
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic