本文介绍了Java:为方便起见,在equals()中使用hashCode()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑以下测试用例,将equals中的hashCode()方法用作方便的快捷方式是不好的做法吗?
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;
}
}
主要方法的输出:
1097562307
1097562307
t1.equals(t2) ? true
推荐答案
一般情况下,比较并不安全hashCode()而不是使用equals()。当equals()返回false时,hashCode()可能返回相同的值,符合。
In general, it's not at all safe to compare the hashCode() instead of using equals(). When equals() returns false, hashCode() may return the same value, per the contract of hashCode().
这篇关于Java:为方便起见,在equals()中使用hashCode()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!