Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Equals method implementation

807580Jun 3 2010 — edited Jul 10 2010
Hi,

I think I understood the basic ideas behind equals and hashcode, but am still unsure about the proper implementation of those methods.
I have a fairly common situation with mutable entity classes that have several business fields and one database id field.

Now, I have two different requirements. First, I need a way to find out if two objects are equal in terms of the values of all members, for example to implement a save reminder on that object. Second, I want to be able to use some of the Collection methods that rely on the equals method like contains(Object o), remove(Object o), indexOf(Object o) etc., but here of course equality is wanted as object db id basis.

So I am obviously facing a dilemma. If I implement equals only on the db id field I can't use it for value equality, but have the correct behaviour on Collection methods. If I define equals on all fields of the class, however, I can define value equality, but can't use the Collection methods on these objects as two objects that have the same db id, but differ in other field values are considered as not equal.

I worked around this problem by implementing equals on all fields and writing my own collection methods that compare the objects on db id basis, but this approach is not very satisfiying because you always have to keep in mind not to use the java collection methods.

I am afraid there is no 100% solution for this problem, but maybe somebody knows some good practices for this.

Thanks, Jan
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Aug 7 2010
Added on Jun 3 2010
8 comments
1,256 views