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的更多相关文章

  1. hashCode()和equals()的用法

    使用hashCode()和equals() hashCode()和equals()定义在Object类中,这个类是所有java类的基类,所以所有的java类都继承这两个方法. hashCode()方法 ...

  2. Java 中正确使用 hashCode 和 equals 方法

    在这篇文章中,我将告诉大家我对hashCode和equals方法的理解.我将讨论他们的默认实现,以及如何正确的重写他们.我也将使用Apache Commons提供的工具包做一个实现. 目录: hash ...

  3. Java中正确使用hashCode() 和equals() 、==

    在java编程中,经常会遇到两个对象中某个属性的比较,常常会用到的方法有: == .equals().但是两者使用起来有什么区别呢? 一.== java中的==是比较两个对象在JVM中的地址.比较好理 ...

  4. (转)Java 中正确使用 hashCode 和 equals 方法

    背景:最近在编写持久化对象时候遇到重写equals和hashCode方法的情况,对这两个方法的重写做一个总结. 链接:https://www.oschina.net/question/82993_75 ...

  5. Java中正确使用hashCode和equals方法

    在这篇文章中,我将告诉大家我对hashCode和equals方法的理解.我将讨论他们的默认实现,以及如何正确的重写他们.我也将使用Apache Commons提供的工具包做一个实现. 目录: hash ...

  6. Apache Commons Lang

    http://commons.apache.org/proper/commons-lang/javadocs/api-release/org/apache/commons/lang3/package- ...

  7. 【java】org.apache.commons.lang3功能示例

    org.apache.commons.lang3功能示例 package com.simple.test; import java.util.Date; import java.util.Iterat ...

  8. 一篇关于apache commons类库的详解

    1.1. 开篇 在Java的世界,有很多(成千上万)开源的框架,有成功的,也有不那么成功的,有声名显赫的,也有默默无闻的.在我看来,成功而默默无闻的那些框架值得我们格外的尊敬和关注,Jakarta C ...

  9. Java工具类 Apache Commons:commons-lang

    Commons Lang The standard Java libraries fail to provide enough methods for manipulation of its core ...

随机推荐

  1. 使用DbVisualizer 8 连接Oracle数据库

    1. 网上下载一个驱动包ojdbc14.jar,放到oracle目录下:...\DbVisualizer-8.0.1\jdbc\oracle\ojdbc14.jar 2. 打开 DbVisualize ...

  2. 杭电ACM2098--分拆素数和

    题目:http://acm.hdu.edu.cn/showproblem.php?pid=2098 这是源码.其实我本不想拿出源码,毕竟源码很容易被复制. 我这里刚开始出错的地方有 0_0_12811 ...

  3. 自定义可判断选项是否正确listbox

    截图如下:        1.实现Converter  获取到listbox,并得到listitem在listbox中的index public class ItemContainerToZIndex ...

  4. 14.Apache配置

    环境:                                                      ↗  atl.example.com  (192.168.1.101) ↗ www.e ...

  5. 《samba搭建win客户端和linux客户端的区别》

    samba服务的搭建 客户的使用系统的不同也导致测试结果的不同. linux系统客户端: security = user or share smbclient -L //192.168.7.113/w ...

  6. Linux磁盘与文件系统概念理解

    磁盘级别概念     这里讲的主要是网上所谓的老式磁盘,它是由一个个盘片组成的,我们先从个盘片结构讲起.如图1所示,图中的一圈圈灰色同心圆为一条条磁道,从圆心向外画直线,可以将磁道划分为若干个弧段,每 ...

  7. WebStorm 快捷键收藏

    快捷键 Ctrl+/ 或 Ctrl+Shift+/ 注释(// 或者/-/ ) Ctrl+X 或 Ctrl+Y 删除一行 Shift+F6 重构-重命名 Alt+~vcs操作 ​ Alt+~ 7关闭重 ...

  8. 解决前端浏览器传JSON对像到服务端后全部变成string类型的方法

    这几天公司用nodejs+mongodb来做些东西,UI用的是kendo UI 碰到一个问题: 举个例子var a={"name":"张三","age ...

  9. java项目中读取src目录下的文件

    private void getUser(String tmpfile){ Properties props = new Properties(); props.load(DbTask.class.g ...

  10. oracle 子查询因子化 浅谈(with的使用)

    近来学习oracle,想要提高自己所写语句的效率和易读性,今天的笔记是关于子查询因子话这么一个东西 因子化的查询不一定可以提高效率,但是一定可以再提高程序的可读性方面成效显著 --with 语句 wi ...