如何重写hashCode()方法?

hashCode()方法在重写时通常按照以下设计原则实现。
(1)把某个非零常数值,例如17,保存在int型变量result中。
(2)对于对象中每一个关键域f(指equals方法中考虑的每一个域)参照以下原则处理。
□ boolean型,计算(f ? 0:1)。
□ byte、char和short型,计算(int)。
□ long 型,计算(int)(f^(f>>>32))。
□ float 型,计算Float.floatToIntBits(afloat)。
□ double型,计算Double.doubleToLongBits(adouble)得到一个long,再执行long型的处理。
□ 对象引用,递归调用它的hashCode()方法。
□ 数组域,对其中每个元素调用它的hashCode()方法。
(3)将上面计算得到的散列码保存到int型变量c,然后执行result=37×result+c。
(4)返回result。
重写hashCode()方法的示例代码如下:
import java.util.Arrays;
public class Unit {
private short ashort;
private char achar;
private byte abyte;
private boolean abool;
private long along;
private float afloat;
private double adouble;
private Unit aObject;
private int[] ints;
private Unit[] units;
//重写equals()方法
public boolean equals(Object o) {
if (o == null)
return false;
if (this.getClass()!= obj.getClass())
return false;
Unit unit = (Unit) o;
return unit.ashort == ashort
&& unit.achar == achar
&& unit.abyte == abyte
&& unit.abool == abool
&& unit.along == along
&& Float.floatToIntBits(unit.afloat) == Float
.floatToIntBits(afloat)
&& Double.doubleToLongBits(unit.adouble) == Double
.doubleToLongBits(adouble)
&& unit.aObject.equals(aObject)
&& equalsInts(unit.ints)
&& equalsUnits(unit.units);
}
private boolean equalsInts(int[] aints) {
return Arrays.equals(ints, aints);
}
private boolean equalsUnits(Unit[] aUnits) {
return Arrays.equals(units, aUnits);
}
//重写hashCode()方法
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 tolong = Double.doubleToLongBits(adouble);
result = 37 * result + (int) (tolong ^ (tolong >>> 32));
result = 37 * result + aObject.hashCode();
result = 37 * result + intsHashCode(ints);
result = 37 * result + unitsHashCode(units);
return result;
}
private int intsHashCode(int[] aints) {
int result = 17;
for (int i = 0; i < aints.length; i++)
result = 37 * result + aints[i];
return result;
}
private int unitsHashCode(Unit[] aUnits) {
int result = 17;
for (int i = 0; i < aUnits.length; i++)
result = 37 * result + aUnits[i].hashCode();
return result;
}
}

猜你喜欢

转载自blog.csdn.net/weixin_42470710/article/details/85934606