Java: Use hashCode() inside of equals() for conven

2019-01-14 12:15发布

Consider the following test case, is it a bad practice to use the hashCode() method inside of equals as a convenient shortcut?

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;
    }   
}

Output from main method:

1097562307
1097562307
t1.equals(t2) ? true

7条回答
该账号已被封号
2楼-- · 2019-01-14 13:14

Very bad! HashCode equality does not mean that equals returns true. The contract is that two objects that are equal must have the same hashCode. But it DOES NOT state the two objects with the same HashCode must be equal.

查看更多
登录 后发表回答