JetBrains Academy: hashCode() and equals() - Kamil-Jankowski/Learning-JAVA GitHub Wiki
JetBrains Academy: hashCode() and equals()
Complex numbers:
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.
public final 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 object){
if (this == object){
return true;
}
if(!(object instanceof ComplexNumber)){
return false;
}
ComplexNumber number = (ComplexNumber) object;
return this.re == number.re &&
this.im == number.im;
}
@Override
public int hashCode(){
return Objects.hash(re, im);
}
}