Maintainable HashCode and Equals Using Apache Commons

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

publicinthashCode() {

finalintprime =31;

intresult =1;

result = prime * result + ((firstName ==null) ?0: firstName.hashCode());

result = prime * result + ((lastName ==null) ?0: lastName.hashCode());

returnresult;

}

@Override

publicbooleanequals(Object obj) {

if(this== obj)

returntrue;

if(obj ==null)

returnfalse;

if(getClass() != obj.getClass())

returnfalse;

Person other = (Person) obj;

if(firstName ==null) {

if(other.firstName !=null)

returnfalse;

}elseif(!firstName.equals(other.firstName))

returnfalse;

if(lastName ==null) {

if(other.lastName !=null)

returnfalse;

}elseif(!lastName.equals(other.lastName))

returnfalse;

returntrue;

}

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

publicbooleanequals(Object obj) {

returnEqualsBuilder.reflectionEquals(this, obj);

}

@Override

publicinthashCode() {

returnHashCodeBuilder.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.