zoukankan      html  css  js  c++  java
  • 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.

  • 相关阅读:
    将地址转换为链接的正则表达式(regex url href)
    [收藏]中国惠普前总裁孙振耀谈人生
    沪江技术团队寻觅新成员,下一位会是你吗?
    来点圣诞气氛
    让VisualSVN Server支持匿名访问
    11月25日博客园南京园友聚会
    [上海俱乐部活动]博文视点与博客园系列图书作者见面会暨.NET技术交流会
    比尔·盖茨在微软的最后一天
    真让人兴奋
    博客园新服务器已下订单
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3585726.html
Copyright © 2011-2022 走看看