Win a copy of The Little Book of Impediments (e-book only) this week in the Agile and Other Processes forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Why override equals() method?

 
Nesan Krish
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Head First EJB book page 297, last sentence: Primary key class must have a valid override of equals()and hashcode(). Please explain the reason for overriding these methods. Thanks in advance!!
 
Roger Chung-Wee
Ranch Hand
Posts: 1683
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
All objects should have a valid equals() method. If the PK class inherits the equals() method, this means that two references to an instance will return true if the equality operator is used. As this is not always correct, the programmer may have to override the equals() method and should almost certainly also overrride the hashCode() method as well.
 
Johnson Chen
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
besides, EJB spec says: PK "class must provide suitable implementation of the hashCode() and equals(Object other) methods to simplify the management of the primary keys by client code" and "container".
 
Johnson Chen
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I ran across a more detail explanation for this, on container level:
"the primary key class must be Serializable. This allows the client and server to exchange keys using by value semantics." ... "Because we will be passing keys by value the issue of object identity comes up. Passing by value means that multiple copies of an object can exist. The server will at times compare keys for equality. The default implementation of equals inherited from the Object class uses identity. This will cause problems when comparing copies, therefore we must override equals. Because we override equals we must also override hashCode." (excerpted from http://users.bigpond.net.au/stephen.davies/papers/beanKeys.html)

On client level, override for the 2 methods in PK class is optional, technically. The spec suggests always use isIdentical() to distinguish entity object references.

Well, taking into account the need in container level, the override is necessary.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic