hashCode() and equals() → Complex numbers
Mon, Sep 16, 2019
One-minute read
Here’s a class ComplexNumber. You need to override its methods equals() and hashCode(). The method equals() should compare two instances of ComplexNumber by the fields re and im. The method hashCode() must be consistent with your implementation of equals().
Implementations of the method hashCode() that return a constant or do not consider a fractional part of re and im, will not be accepted.
ComplexNumber a = new ComplexNumber(1, 1);
ComplexNumber b = new ComplexNumber(1, 1);
// a.equals(b) must return true
// a.hashCode() must be equal to b.hashCode()
Solution
class ComplexNumber {
private final double re;
private final double im;
public ComplexNumber(double re, double im) {
this.re = re;
this.im = im;
}
public double getRe() {
return re;
}
public double getIm() {
return im;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ComplexNumber that = (ComplexNumber) o;
return Double.compare(that.re, re) == 0 &&
Double.compare(that.im, im) == 0;
}
@Override
public int hashCode() {
return Objects.hash(re, im);
}
}