When overriding the equals method, we use only "Object obj" as a parameter?

I was charged with the following:

Override the equals () and hashCode () methods respectively in your Rational Numbers Class.

Further it expands. My question is: when you override the equals method, do you change the passed parameter? If it checks logical equivalence, I did the following:

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

I'm not sure if this will be the way to override the method. If so, then when you override the hashcode method, is it just a simple job of choosing a good code for assigning the hash codes?

Also, this is the hash code that I created. Is it on 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
}
+4
source share
3

equals Object equals. , 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;
}

, @Override , , . , , - ( Rational /, boolean equals(Rational rhs)).

+9

, , equals(Object),

public boolean equals(Object o) {
    return o instanceof Rational && equals((Rational) o);
}

equals(Object): .

List list = Arrays.asList(1, "Hello", new Rational(1, 2));
// needs to be able to compare with 1 and "Hello"
list.contains(new Rational(1, 2)); 
+5

- "", - , .

, , , :

Object r = new Rational();
boolean b = r.equals("x");

Rational, , String Object.equals(Object), , String .

, Rational String - ! Java. , , "" .

, , , "obj" Rational: Rational rhs = (Rational)obj; - , , instanceof , obj Rational, - (, String!).

if (obj instanceof Rational) {
    Rational r = (Rational)obj;
    ....

, :

  • , r.equals("x"): : " , r Rational"? "": Java . , . , , , , , "" - , Rational .
  • equals , : null, , .. instanceof - getClass() == obj.getClass() . - Java . : hashCode Java?
  • , Java , " ". myMethod(String) myMethod(Object) (.. - ), . , Java ; . : contra-variance ?

hashCode(): , , , hashcode . equals 95% .

Edit: in the updated question, you provide a hashCode method that ... thinks a lot! You can split it into return (31 + num) * 31 + denom;or similar. Because of this, I use 31: Why does the Java () hash code in String use 31 as a multiplier? .

0
source

All Articles