mat_boy
mat_boy

Reputation: 13676

About Apache Commons EqualsBuilder and HashCodeBuilder and null values

The classes EqualsBuilder and HashCodeBuilder from the Apache Commons Lang library can be used for object comparison purposes.

E.g., one can test equality between two Person objects like follows:

Person p1 =...;
Person p2 =...;
boolean equals = new EqualsBuilder().
        append(p1.name, p2.name).
        append(p1.secondname, p2.secondname).
        append(p1.surname, p2.surname).
        append(p1.age, p2.age).
        isEquals();

Suppose that a field is not mandatory, e.g. secondname. How does EqualsBuilder and HasCodeBuilder handle this fact? Is the comparison done on this field or not? Or the comparison on a null field can be skipped as a special option?

Upvotes: 1

Views: 4267

Answers (1)

JB Nizet
JB Nizet

Reputation: 691953

These two methods will consider p1.name and p2.name to be equal if they're both null. Here's the relevant part of the freely available source code:

public EqualsBuilder append(Object lhs, Object rhs) {
    if (isEquals == false) {
        return this;
    }
    if (lhs == rhs) {
        return this;
    }
    ...

Upvotes: 4

Related Questions