http://zhangjunhd.blog.51cto.com/113473/71571/
package com.demo.bean;
import java.util.Arrays;
public class Unit {
private byte abyte;
private short ashort;
private int aint;
private long along;
private boolean abool;
private float afloat;
private double adouble;
private char achar;
private Unit unit;
private int[] ints;
private Unit[] units;
/***
* [1]把某个非零常数值,例如17,保存在int变量result中;
* [2]对于对象中每一个关键域f(指equals方法中考虑的每一个域):
* [2.1]boolean型,计算(f ? 0 : 1);
* [2.2]byte,char,short型,计算(int);
* [2.3]long型,计算(int) (f ^ (f>>>32));
* [2.4]float型,计算Float.floatToIntBits(afloat);
* [2.5]double型,计算Double.doubleToLongBits(adouble)得到一个long,再执行[2.3];
* [2.6]对象引用,递归调用它的hashCode方法;
* [2.7]数组域,对其中每个元素调用它的hashCode方法。
* [3]将上面计算得到的散列码保存到int变量c,然后执行 result=37*result+c; [4]返回result。
*/
@Override
public int hashCode() {
int result = 17;
result = 37 * result + (int) abyte;
result = 37 * result + (int) ashort;
result = 37 * result + (int) aint;
result = 37 * result + (int) achar;
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 + unit.hashCode();
result = 37 * result + intsHashCode(ints);
result = 37 * result + unitsHashCode(units);
return result;
}
@Override
public boolean equals(Object object) {
// TODO Auto-generated method stub
if (!(object instanceof Unit)) {
return false;
}
Unit uni = (Unit) object;
return unit.abool == abool
&& uni.abyte == abyte
&& uni.ashort == ashort
&& uni.aint == ashort
&& uni.along == along
&& uni.afloat == afloat
&& Float.floatToIntBits(uni.afloat) == Float
.floatToIntBits(afloat)
&& Double.doubleToLongBits(uni.adouble) == Double
.doubleToLongBits(adouble) && uni.unit.equals(unit)
&& uni.equalsInts(unit.ints) && uni.equalsUnits(units);
}
private boolean equalsInts(int[] aints) {
return Arrays.equals(ints, aints);
}
private boolean equalsUnits(Unit[] aUnits) {
return Arrays.equals(units, aUnits);
}
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;
}
}