1. 程式人生 > >Java-改寫equals 必須改寫hashChode()

Java-改寫equals 必須改寫hashChode()

class H {
private int x;
private int y;
private float z;
private double t;

H(int x, int y,float z, double t) {
this.x = x;
this.y = y;
this.z = z;
this.t = t;
}

public boolean equals(Object o) {
if (o == null) return false;
if (o == this) return true;
if (!(o instanceof H)) return false;
H p = (H)o;
int dz = Float.floatToIntBits(z);
long ft = Double.doubleToLongBits(t);
return ((this.x == p.x) && (this.y == p.y) && (dz == Float.floatToIntBits(p.z)) && (ft == Double.doubleToLongBits(p.t)));
//return ((this.x == p.x) && (this.y == p.y) && (this.z == p.z) && (this.t == p.t));
}

public int hashCode() {
int result = 17;
result = 37*result + x;
result = 37*result + y;
result = 37*result + Float.floatToIntBits(z);
result = 37*result + (int)Double.doubleToLongBits(t);
return (int)result;
}

public static void main(String[] args) {

H p1 = new H(1,1,-0.0f,0.000000000000000000001);
H p2 = new H(1,1,-0.0f,0.000000000000000000001);
System.out.println(p1.equals(p2));
System.out.println(p1.hashCode());
System.out.println(p2.hashCode());
}
}
===================================================================
true
-1946841466
-1946841466