Maintainable HashCode and Equals Using Apache Commons

Java hashCode and equals methods can be tricky to implement correctly. Fortunately, all majors IDEs allow generating them. For example, this is how they look like for a class with two attributes when generated in Eclipse:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + ((firstName == null) ? 0 : firstName.hashCode());
    result = prime * result + ((lastName == null) ? 0 : lastName.hashCode());
    return result;
}
 
@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    Person other = (Person) obj;
    if (firstName == null) {
        if (other.firstName != null)
            return false;
    } else if (!firstName.equals(other.firstName))
        return false;
    if (lastName == null) {
        if (other.lastName != null)
            return false;
    } else if (!lastName.equals(other.lastName))
         return false;
    return true;
}

It’s better than writing all this by hand but I still don’t like it. Here’s why:

  • It makes it way too easy to forget about updating them after adding a new field
  • It lowers the code coverage when not properly tested
  • It is just plain ugly

The first reason is the most important one. Having to remember about updating generated equals and hashCode methods when adding new fields increases the maintenance cost. Forgetting to do so may result in nasty bugs.

Because of that I never use generated hashCode and equals. I use builders from Apache Commons instead. In the most basic scenario they look like this:

1
2
3
4
5
6
7
8
9
@Override
public boolean equals(Object obj) {
    return EqualsBuilder.reflectionEquals(this, obj);
}
 
@Override
public int hashCode() {
    return HashCodeBuilder.reflectionHashCode(this);
}

They retrieve values using reflection from all fields except for transient and static ones. Most of the time this is precisely what I want. If you need some customizations check out the API documentation.

posted on 2014-03-07 09:18  Step-BY-Step  阅读(201)  评论(0编辑  收藏  举报

导航