So Im having a problem with my equals class

public boolean equals(Object other) {
    if (other.equals(this.numerator) &&  other.equals(this.denominator))
        return true;
    else
        return false;
}

it gives me the result of 9/2 eq 9/2= false.

(Rest of my code for referees ) https://gist.github.com/anonymous/6604f427cc9d17391478

What am i doing wrong?

I edited the code but still and dealing with an error of boolean and int

public boolean equals(Object other) {
    if (other.equals(this.numerator) == getNumerator() &&  other.equals(this.denominator)== getDenominator())
        return true;
    else
        return false;
}
有帮助吗?

解决方案

When implementing equals, before checking if the objects are equal you should consider the next scenarios:

  • The two are actually references to the same object
  • The other object is null
  • The other object is an instance of a different type

and when checking equality between the two objects you should consider the nullness of every field involved in the comparison too. In most IDEs equals can be generated automatically, in eclipse:

Alt + Shift + s --> Generate hashCode() and equals()

the next is generated by eclipse:

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        A other = (A) obj;
        if (denominator == null) {
            if (other.denominator != null)
                return false;
        } else if (!denominator.equals(other.denominator))
            return false;
        if (numerator == null) {
            if (other.numerator != null)
                return false;
        } else if (!numerator.equals(other.numerator))
            return false;
        return true;
    }

其他提示

return
    (other.numerator.equals(this.numerator)
    && 
    other.denominator.equals(this.denominator))

Of couse this doesn't consider that 1/2 == 2/4.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top