I have a java project where I need both identity comparison (are the 2 references the same) and equality comparison (do both object contain the same data).
My solution is to not override equals/hashcode, and to add an isEqual method to my objects.
Is there a better pattern to deal with this situation?
EDIT:
Here is more information about this particular need.
By default we have:
equalsperforming an identity check (==)containsbeing implemented in terms ofequals, therefore using ==
But for my usage I would want:
equalsto perform an equality check (objects contain the same data)containsto remain implemented with ==
I can’t have both at the same time, so one solution is to implement my
own equality check and have:
containsstaying the same, using ==- implementing
isEqualand use it instead ofequals
another solution is to implement my own contains that uses ==:
- implementing
customContainsto use == and use it instead ofcontains - Overriding
equalsto check whether objects contain the same data
Which is best? Is there another better way to do this?
The best pattern to do this is to follow the specification of the language. Override equals and hashcode, and do not roll your own equality UNLESS and this is a big unless, no one outside of you will ever use this code AND it will never ever ever change.
If you want to wrap them in a function called
isEqual, the hashcode and equals methods that is, this is another approach, but it still means you are overriding equals and hashcode, which you claim you do not want to do.Essentially what you are doing is creating a very rigid and/or broken API, that will not see much usage as it will be difficult to utilize as your
isEqualfunction could be quite non-deterministic.