Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

public boolean equals(Object other)

Tags:

java

This is for a Fraction program. I have private ints num and den, Fraction, and FractionInterface - the standard homework problem. I have done pretty much everything and now have been stuck for a few hours on the equals method. Since other is an Object, I can't equate it to Fraction. Here's what I have:

public boolean equals(Object other){        
     if (other == this){
         return true;
     } else {
         return false;
     }
}

This compiles but it gives incorrect results:

1/2 eq 1/2 = true
1/2 eq 1/2 = true
1/2 eq 1/2 = false
1/2 eq 1/2 = false

If I try other == Fraction, it doesn't compile. Thanks for any help!

like image 915
Boris4ka Avatar asked Nov 05 '22 04:11

Boris4ka


2 Answers

You can test if other is an instance of FractionInterface and use a cast:

public boolean equals(Object other){        
     if (other == this){
         return true;
     } else if (other instanceof FractionInterface) {
         FractionInterface fOther = (FractionInterface) other;
         // compare numerator and denominator...
     } else {
         return false;
     }
}

Note that instanceof will be false if other == null, so there's no need for a separate null check.

like image 144
Ted Hopp Avatar answered Nov 09 '22 16:11

Ted Hopp


Try this out:

First, cast the other object

Fraction otherFraction = (Fraction) other;

Then, determine the condition that the two fractions are equivalent. This will include some logic involving the comparing of numerator and denominators (expect to use getNum() and getDen() for the otherFraction.

like image 37
Prashant Kumar Avatar answered Nov 09 '22 16:11

Prashant Kumar