• Post Reply Bookmark Topic Watch Topic
  • New Topic

Why hashCode() and equals() should be implemented in PrimaryKey class  RSS feed

 
great veera
Greenhorn
Posts: 24
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ranchies,
can anyone tell me why the hashCode() and equals() should be implemented in primarykey class.I have gone thro' the ejbmatrix pdf it says these 2 methods are recommended and should be implemented.
And moreover i 've gone thro' oreilly's link http://www.oreilly.com/catalog/entjbeans/chapter/appd.html
which says
the new specification requires the primary key class to implement the Object.equals() and Object.hashCode() methods to ensure that these methods evaluate properly when comparing keys and storing them in a java.util.Hashtable .....
if this is the case why the keys should be compared and stored in Hashtable..
Pl anyone clarify me.
TIA
veera
 
Peter den Haan
author
Ranch Hand
Posts: 3252
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Entity beans are identified by their primary key. Not only from the perspective of the EJB developer, but also from the perspective of the EJB container.
Think for example of the findByPrimaryKey() method in the home interface. The container needs an efficient way to search for the primary key you've given, to see if it already has an entity bean for that key in the instance pool. If it finds the key, it needs to retrieve the actual bean. All of this has to be a completely generic, as the primary key may be any Java class.
If you know your Collections framework, this description just screams the word "HashMap". For the HashMap to work, the key object needs to implement hashCode() and equals().
- Peter

[This message has been edited by Peter den Haan (edited May 21, 2001).]
 
sandy gupta
Ranch Hand
Posts: 228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Peter,
That was a very good answer to a very good Q but i would like to know more. Cud you pass on a URL for my benefit and for all of the rest.
Thanks
Sahil
 
Paulo Aquino
Ranch Hand
Posts: 202
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes PETER, i hope you can pass to us the URL. Thanks...
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!