1.java計算公式
@Override public int hashCode() { //設置初始值 int result = 17; //假設有效域為: name,age,idCardNo,incomeAnnual,sex,brithDay int c = 0; //計算name (String為對象類型,他的計算直接調用本身的hashCode) c = name.hashCode(); result = result * 37 + c; //計算age (int/byte/char/short類型,他的計算直接調用本身的值) c = this.getAge(); result = result * 37 + c; //計算idCardNo (long類型,他的計算 (int)(field^(field >>> 32)) 無符號右移32位) c = (int) (this.idCardNo ^ (this.idCardNo >>> 32)); result = result * 37 + c; //計算 incomeAnnual (double類型,他的計算 Double.doubleToLongBits(field)后,再按Long類型計算 ) //(float類型,他的計算 Float.floatToIntBits(field) ) long tmp = Double.doubleToLongBits(this.incomeAnnual); c = (int) (tmp ^ (tmp >>> 32)); result = result * 37 + c; //計算 sex (sex為boolean類型,他的計算直接調用 c=sex?1:0) c = this.isSex() ? 1 : 0; result = result * 37 + c; //計算 brithDay (brithDay為Date對象類型,他的計算直接調用 本身的hashCode) c = this.getBirthDay().hashCode(); result = result * 37 + c; return result; }
2. .net計算公式
public class HashCodeTest { public static void Excute() { var man = new Man() { Age = 10, BirthDay = new DateTime(1950,1,1), IdCardNo = 2139095040, IncomeAnnual = 10000000.5, Name = "Aven", Sex = true }; var hasCode = man.GetHashCode(); Console.WriteLine(hasCode); } } class Man { public long IdCardNo { get; set; } public int Age { get; set; } public string Name { get; set; } public double IncomeAnnual { get; set; } public bool Sex { get; set; } public DateTime BirthDay { get; set; } public override int GetHashCode() { //設置初始值 int result = 17; //假設有效域為: name,age,idCardNo,incomeAnnual,sex,brithDay int c = 0; //計算name (String為對象類型,他的計算直接調用本身的hashCode) c = Name.GetHashCode(); result = result * 37 + c; //計算age (int/byte/char/short類型,他的計算直接調用本身的值) c = this.Age; result = result * 37 + c; //計算idCardNo (long類型,他的計算 (int)(field^(field >> 32)) 有符號右移32位,符號位不移動) c = (int)(this.IdCardNo ^ (this.IdCardNo >> 32)); result = result * 37 + c; //計算 incomeAnnual (double類型,他的計算 BitConverter.DoubleToInt64Bits(field)后,再按Long類型計算 ) //(float類型,他的計算 BitConverter.ToInt32(BitConverter.GetBytes(this.IncomeAnnual),0) ) long tmp = BitConverter.DoubleToInt64Bits(this.IncomeAnnual); c = (int)(tmp ^ (tmp >> 32)); result = result * 37 + c; //計算 sex (sex為boolean類型,他的計算直接調用 c=sex?1:0) c = this.Sex ? 1 : 0; result = result * 37 + c; //計算 brithDay (brithDay為Date對象類型,他的計算直接調用 本身的hashCode) c = this.BirthDay.GetHashCode(); result = result * 37 + c; return result; } }
