Java:为了方便起见,在 equals() 中使用 hashCode()?

标签 java equals hashcode

考虑下面的测试用例,在 equals 中使用 hashCode 方法作为一种方便的快捷方式是不是一种不好的做法?

public class Test 
{    
    public static void main(String[] args){
        Test t1 = new Test(1, 2.0, 3, new Integer(4));
        Test t2 = new Test(1, 2.0, 3, new Integer(4));
        System.out.println(t1.hashCode() + "\r\n"+t2.hashCode());
        System.out.println("t1.equals(t2) ? "+ t1.equals(t2));
    }
    
    private int myInt;
    private double myDouble;
    private long myLong;
    private Integer myIntObj;
    
    public Test(int i, double d, long l, Integer intObj ){
        this.myInt = i;
        this.myDouble = d;
        this.myLong = l;
        this.myIntObj = intObj;
    }
    
    @Override
    public boolean equals(Object other)
    {        
        if(other == null) return false;
        if (getClass() != other.getClass()) return false;            
        
        return this.hashCode() == ((Test)other).hashCode();//Convenient shortcut?
    }

    @Override
    public int hashCode() {
        int hash = 3;
        hash = 53 * hash + this.myInt;
        hash = 53 * hash + (int) (Double.doubleToLongBits(this.myDouble) ^ (Double.doubleToLongBits(this.myDouble) >>> 32));
        hash = 53 * hash + (int) (this.myLong ^ (this.myLong >>> 32));
        hash = 53 * hash + (this.myIntObj != null ? this.myIntObj.hashCode() : 0);
        return hash;
    }   
}

主要方法的输出:

1097562307
1097562307
t1.equals(t2) ? true

最佳答案

一般来说,比较 hashCode 而不是使用 equals 是不安全的。当 equals 返回 false 时,hashCode 可能 返回相同的值,根据 contract of hashCode .

关于Java:为了方便起见,在 equals() 中使用 hashCode()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7417668/

相关文章:

java - CascadeType.Persist 没有按预期工作

java - Android 位置的多个运行时权限

java - JAVA 的 equals 方法总是返回 true

java - 使用 HashMap 统计实例

java - 需要写一定的方法

java - 如何通过 Maven 命令重新运行 TestNG 失败的测试

java - 如何制作一个遵循规则的二维字符串数组,根据java中的输入创建不同的路径?

java - 为非常简单的类实现 `hashCode()`

c# - 如何为一对 3D 向量实现 GetHashCode

Java HashSet 包含不起作用的函数