I have implemented a class to model rational numbers in java, it has two integers to model numerator and denominator. I am required to override the hashcode method of Object, so the same numbers have the same hash code.
I have defined my equals() method like this:
public boolean equals(Object obj) {
Racional r = null;
if (obj instanceof Racional) {
r = (Racional) obj;
} else {
return false;
}
return r.getDenominador() * this.numerador == r.getNumerador() * this.denominador;
}
Regarding this:
Would returning numerator * denominator be a good approach?
Should equivalent rational numbers (like 1/4 and 2/8) return the same hashcode?
It all depends on how you implemented your
equalsmethod. Ifobj1.equals(obj2)istrue,obj1.hashCode() == obj2.hashCode()should also betrue. I would probably just usenew Double((double) numerator / denominator).hashCode()for my hash, but your requirements might not allow that./edit
Using
numerator * denominatorfor your hash would be an invalid approach given yourequalsmethod. Using your example of1/4and2/8,1/4.equals(2/8)would returntrue, but1/4.hashCode() == 2/8.hashCode()would evaluate to4 == 16, and returnfalse.