首页 > 其他 > 详细

Maintainable HashCode and Equals Using Apache Commons

时间:2014-03-11 14:18:11      阅读:452      评论:0      收藏:0      [点我收藏+]

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.

Maintainable HashCode and Equals Using Apache Commons,布布扣,bubuko.com

Maintainable HashCode and Equals Using Apache Commons

原文:http://www.cnblogs.com/reynold-lei/p/3585726.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!