Java equal 和 hashcode
在Java中,判断两个对象相等用equal。(废话)
前提是必须该对象重写了equal,以及最好将hashcode一起重写掉。
因为要符合"相等的对象必须具有相等的散列码"。反之,如果不写,那么例如在HashMap中,该对象充当key必然会出现"对象相同但散列吗不同而导致不同的key"。
刚开始写hashcode,无从下手,虽然有一堆规则,但不好记(本人健忘)。遂总结一下1点。
“所有数据类型都向int靠拢”
所以:
1.boolean >> (0, 1)
2.byte, char, short >> (int)
3.long >> (int) (x ^ (x >>>32))
4.float >> Float.floatToIntBits( f )
5.double >> Double.doubleToLongBits( b ) >> (int) (x ^ (x >>>32))
6.object >> object.hashCode()
7.arrays >> 遍历,递归。
code:
public int hashCode() { int result = 17; result = 37 * result + (int) ashort; result = 37 * result + (int) achar; result = 37 * result + (int) abyte; result = 37 * result + (abool ? 0 : 1); result = 37 * result + (int) (along ^ (along >>> 32)); result = 37 * result + Float.floatToIntBits(afloat); long blong= Double.doubleToLongBits(adouble); result = 37 * result + (int) (blong^ (blong >>> 32)); result = 37 * result + aObj.hashCode(); return result; }
数组的话
1 private int intsHashCode(int[] ints) { 2 int result = 17; 3 for (int i = 0; i < ints.length; i++) 4 result = 37 * result + ints[i]; 5 return result; 6 } 7 8 private int objsHashCode(Object[] objs) { 9 int result = 17; 10 for (Object o : objs) { 11 result = 37 * result + o.hashCode(); 12 } 13 return result; 14 }

浙公网安备 33010602011771号