Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementation equals() method design pattern

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;
like image 489
Pavel Avatar asked Nov 23 '25 02:11

Pavel


2 Answers

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.

like image 160
Nandkumar Tekale Avatar answered Nov 25 '25 14:11

Nandkumar Tekale


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.

like image 37
dvsander Avatar answered Nov 25 '25 16:11

dvsander



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!