When overriding the equals method, do we only use 'Object obj' as the parameter?

Viewed 1979

I've been tasked with this:

Override the equals() and hashCode() methods appropriately in your Rational Numbers class.

It further expands on this. My question is, when you override the equals method, do you change the parameter passed in? If it checks for logical equivalence then I've done the following:

public boolean equals(Rational rhs){
    if(this.num == rhs.num && this.denom == rhs.denom){
        return true;
    }
    return false;
}

I'm unsure if this is the way to go when overriding the method. If it is, then when you override the hashcode method, is it just a simple job of picking a good piece of code to assign hashcodes?

Additionally, this is the hashcode I've created. Is this along the right lines?

@Override
public int hashCode(){
    int hc = 17;
    hc = 37 * hc + ((num == 0 && denom == 0) ? 0 : num);
    return 37 * hc + denom;


    //boolean b = cond ? boolExpr1 : boolExpr2;
    //if cond true then b=boolExpr1 else b=boolExpr2
}
3 Answers
Related