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