How to implement equals() and hashCode() methods in Java[reproduced]

Part I:
equals() (javadoc) must define an equivalence relation (it must be reflexive, symmetric, and transitive). In addition, it must be consistent (if the objects are not modified, then it must keep returning the same value). Furthermore, o.equals(null) must always return false.

hashCode() (javadoc) must also be consistent (if the object is not modified in terms of equals(), it must keep returning the same value).

The relation between the two methods is:

Whenever a.equals(b), then a.hashCode() must be same as b.hashCode().
In practice:

If you override one, then you should override the other.

Use the same set of fields that you use to compute equals() to compute hashCode().

Use the excellent helper classes EqualsBuilder and HashCodeBuilder from the Apache Commons Lang library. An example:

public class Person {
    private String name;
    private int age;
    // ...

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
            // if deriving: appendSuper(super.hashCode()).
            append(name).
            append(age).
            toHashCode();
    }

    @Override
    public boolean equals(Object obj) {
       if (!(obj instanceof Person))
            return false;
        if (obj == this)
            return true;

        Person rhs = (Person) obj;
        return new EqualsBuilder().
            // if deriving: appendSuper(super.equals(obj)).
            append(name, rhs.name).
            append(age, rhs.age).
            isEquals();
    }
}

Also remember:
When using a hash-based Collection or Map such as HashSet, LinkedHashSet, HashMap, Hashtable, or WeakHashMap, make sure that the hashCode() of the key objects that you put into the collection never changes while the object is in the collection. The bulletproof way to ensure this is to make your keys immutable, which has also other benefits.

PartII:

The commons/lang builders are great and I have been using them for years without noticeable performance overhead (with and without hibernate). But as Alain writes, the Guava way is even nicer:

Here‘s a sample Bean:

public class Bean{

    private String name;
    private int length;
    private List<Bean> children;

}
Here‘s equals() and hashCode() implemented with Commons/Lang:

@Override
public int hashCode(){
    return new HashCodeBuilder()
        .append(name)
        .append(length)
        .append(children)
        .toHashCode();
}

@Override
public boolean equals(final Object obj){
    if(obj instanceof Bean){
        final Bean other = (Bean) obj;
        return new EqualsBuilder()
            .append(name, other.name)
            .append(length, other.length)
            .append(children, other.children)
            .isEquals();
    } else{
        return false;
    }
}
and here with Guava:

@Override
public int hashCode(){
    return Objects.hashCode(name, length, children);
}

@Override
public boolean equals(final Object obj){
    if(obj instanceof Bean){
        final Bean other = (Bean) obj;
        return Objects.equal(name, other.name)
            && length == other.length // special handling for primitives
            && Objects.equal(children, other.children);
    } else{
        return false;
    }
}

As you can see the Guava version is shorter and avoids superfluous helper objects. In case of equals, it even allows for short-circuiting the evaluation if an earlier Object.equal() call returns false (to be fair: commons / lang has an ObjectUtils.equals(obj1, obj2) method with identical semantics which could be used instead of EqualsBuilder to allow short-circuiting as above).

So: yes, the commons lang builders are very preferable over manually constructed equals() and hashCode() methods (or those awful monsters Eclipse will generate for you), but the Guava versions are even better.

And a note about Hibernate:

be careful about using lazy collections in your equals(), hashCode() and toString() implementations. That will fail miserably if you don‘t have an open Session.

Note (about equals()):

a) in both versions of equals() above, you might want to use one or both of these shortcuts also:

@Override
public boolean equals(final Object obj){
if(obj == this) return true; // test for reference equality
if(obj == null) return false; // test for null
// continue as above
b) depending on your interpretation of the equals() contract, you might also change the line(s)

if(obj instanceof Bean){
to

// make sure you run a null check before this
if(obj.getClass() == getClass()){
If you use the second version, you probably also want to call super(equals()) inside your equals() method. Opinions differ here, the topic is discussed in this question:

right way to incorporate superclass into a Guava Objects.hashcode() implementation?
(although it‘s about hashCode(), the same applies to equals())

Note (inspired by Comment from kayahr)

Objects.hashCode(..) (just as the underlying Arrays.hashCode(...)) might perform badly if you have many primitive fields. In such cases, EqualsBuilder may actually be the better solution.

时间: 2024-10-01 02:26:08

How to implement equals() and hashCode() methods in Java[reproduced]的相关文章

java学习中,object 对象的使用(toString、equals、hashCode)(java 学习中的小记录)

java学习中,object 对象的使用(java 学习中的小记录)作者:王可利(Star·星星) object 对象(参考API学习) 重点掌握三个方法: 1.toString 返回该对象的字符串表示. 2.equals(object obj)指示其他某个对象是否与这个对象相等. 3.hashCode() 返回对象的哈希码. 详见代码的注释分析(一个是Person类重写方法,一个是Star类使用方法) Star类代码: 1 package study; 2 3 public class sta

看Java中==、equals、hashCode的来龙去脉

我有一个哥们去参加了面试,面试官这样问一个Java问题: 你说一下java对象的equals方法调用什么方法呢?我这个哥们想了想,回答说"应该是比较的引用".听了这个答案之后,那个面试官摇头晃脑的说:"不对,你回答的不对,equals方法调用的是hashCode方法".于是乎,我那个技术还不错的哥们就悲壮地栽在这道题目上了. 今天晚上,西安历史上少有的热,那就好好总结一下这个题目的来龙去脉好了,也方便给后面的朋友们提个醒,不要栽在这么简单的问题上.你说这个面试官回答

Java 中的 ==, equals 与 hashCode 的区别与联系

一.概述 1.概念 == : 该操作符生成的是一个boolean结果,它计算的是操作数的值之间的关系 equals : Object 的 实例方法,比较两个对象的content是否相同 hashCode : Object 的 native方法 , 获取对象的哈希值,用于确定该对象在哈希表中的索引位置,它实际上是一个int型整数 二.关系操作符 == 1.操作数的值 基本数据类型变量 在Java中有八种基本数据类型: 浮点型:float(4 byte), double(8 byte) 整型:byt

equals与hashCode的剖析

Java中有两条众所周知的规定 1)对象相等必须有相等的hashCode 2)两个对象不相等,hashCode可能相同 但是为什么有这两个规定呢,不可能凭空产生,总是有原因的,下面我们就来分析两条规定的由来 1. 哈希码 首先这两条规定和哈希码密不可分,甚至可以说这两条规定就是为了对象的hashCode()实现. hashCode()方法返回的就是该对象的哈希码,是一个整数,通过该哈希码我们可以确定该对象在散列存储结构中的地址(比如Set,HashMap的key),快速索引该对象,查找效率极高.

一次性搞清楚equals和hashCode

前言 在程序设计中,有很多的“公约”,遵守约定去实现你的代码,会让你避开很多坑,这些公约是前人总结出来的设计规范. Object类是Java中的万类之祖,其中,equals和hashCode是2个非常重要的方法. 这2个方法总是被人放在一起讨论.最近在看集合框架,为了打基础,就决定把一些细枝末节清理掉.一次性搞清楚! 下面开始剖析. public boolean equals(Object obj) Object类中默认的实现方式是  :   return this == obj  .那就是说,

Java:重写equals()和hashCode()

以下内容总结自<Effective Java>. 1.何时需要重写equals() 当一个类有自己特有的“逻辑相等”概念(不同于对象身份的概念). 2.设计equals() [1]使用instanceof操作符检查“实参是否为正确的类型”. [2]对于类中的每一个“关键域”,检查实参中的域与当前对象中对应的域值. [2.1]对于非float和double类型的原语类型域,使用==比较: [2.2]对于对象引用域,递归调用equals方法: [2.3]对于float域,使用Float.float

Java 重写 equals 与 hashCode 的注意事项

为什么重写 equals 的时候必须重写 hashCode 大家可能从很多教程中了解到: SUN官方的文档中规定"如果重定义equals方法,就必须重定义hashCode方法,以便用户可以将对象插入到散列(哈希)表中" 那么 SUN 公司是出于什么考虑做了这个规定呢? 在集合框架中的HashSet,HashTable和HashMap都使用哈希表的形式存储数据,而hashCode计算出来的哈希码便是它们的身份证.哈希码的存在便可以: 快速定位对象,提高哈希表集合的性能. 只有当哈希表中对

java equals()和hashCode()重写总结

在实际开发中有时候会遇到需要比较同一个类的不同实例对象的场景,一般情况下继承自Object父类的equals()和hashCode()可以满足需求,但却不能满足所有的场景,比如只需要使用少数几个对象属性来判断比较是否是同一个对象,这时我们就需要自定义的equals()和hashCode()实现来进行重写覆盖Object中的方法. 1. equals()方法重写注意事项 a. 自反性:对于任意的引用值x,x.equals(x)一定为true. b. 对称性:对于任意的引用值x 和 y,当x.equ

【转】Java中==、equals、hashcode的区别与重写equals以及hashcode方法实例

原文地址:http://www.cnblogs.com/luankun0214/p/4421770.html 感谢网友的分享,记录下来只为学习. 1.重写equals方法实例   部分代码参考http://blog.csdn.net/wangloveall/article/details/7899948 重写equals方法的目的是判断两个对象的内容(内容可以有很多,比如同时比较姓名和年龄,同时相同的才是用一个对象)是否相同 如果不重写equals,那么比较的将是对象的引用是否指向同一块内存地址