Java Language Implement equals() method


Example

To implement the equals method of an object easily you could use the EqualsBuilder class.

Selecting the fields:

@Override
public boolean equals(Object obj) {

    if(!(obj instanceof MyClass)) {
        return false;
    }
    MyClass theOther = (MyClass) obj;
    
    EqualsBuilder builder = new EqualsBuilder();
    builder.append(field1, theOther.field1);
    builder.append(field2, theOther.field2);
    builder.append(field3, theOther.field3);
    
    return builder.isEquals();
}

Using reflection:

@Override
public boolean equals(Object obj) {
    return EqualsBuilder.reflectionEquals(this, obj, false);
}

the boolean parameter is to indicates if the equals should check transient fields.

Using reflection avoiding some fields:

@Override
public boolean equals(Object obj) {
    return EqualsBuilder.reflectionEquals(this, obj, "field1", "field2");
}