Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
}
like image 826
Andrew Coates Avatar asked Dec 07 '22 23:12

Andrew Coates


1 Answers

Your equals method doesn't override Object's equals. In order to override it, the argument must be an Object.

@Override
public boolean equals(Object other){
    if (!(other instanceof Rational))
        return false;
    Rational rhs = (Rational) other;
    if(this.num == rhs.num && this.denom == rhs.denom){
        return true;
    }
    return false;
}

Note that the @Override annotation helps you detect cases in which you meant to override a method but overloaded it instead. If you put that annotation in your original method, you'll get a compilation error, since your method is not overriding any method (assuming your Rational class doesn't extend or implement some class/interface that contains a boolean equals(Rational rhs) method).

like image 162
Eran Avatar answered Jan 10 '23 22:01

Eran