Is there any design pattern (or idiom) that helps to implement equals() method in Java?
That task is'n so hard but in most cases it's about the same... That's why I guess that there is a pattern but I didn't find it.
UPDATE
I chose the method: generate equals() method in Eclipse but... I found a good way (in AbstractList) to make that generated code better:
if (!(attributes ==null ? other.attributes==null : attributes.equals(other.attributes)))
return false;
instead of generated:
if (attributes == null) {
if (other.attributes != null)
return false;
} else if (!attributes.equals(other.attributes))
return false;
Generally to implement equals() method, what I do is : I generate those from Eclipse as Eclipse can generate hashCode, toString and equals() methods very well.
I always use following code:
if (null == obj) return false;
if (this == obj) return true;
if (!(object instanceof MyClass)) return false;
MyClass that = (MyClass) obj;
EqualsBuilder eb = new EqualsBuilder();
eb.append(this.businessKey, that.businessKey);
return eb.isEquals();
...
I never use technical keys like sequences or pk's, always business fields. Therefore I don't believe this can be made generic but must be made specific to any given Class.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With