0

Below code returns false. Trying to make Equation object act as a key in a custom HashMap. Pretty sure method overrides are implemented correctly, hashCode is the exact same between the two equation instances. What is exactly wrong?

class Solution {
    public boolean maxPoints(int[][] points) {
        Map<Equation, Integer> map = new HashMap<>();
        Equation eq1 = new Equation(1, 2);
        Equation eq2 = new Equation(1, 2);
        map.put(eq1, 1);
        if (map.containsKey(eq1)) return true;
        return false;
    }
    
    class Equation {
        private int slope;
        private int yIntercept;
        public Equation(int slope, int yIntercept) {
            this.slope = slope;
            this.yIntercept = yIntercept;
        }
        
        public boolean equals(Equation other) {
            if (other == this) return true;
            return (this.slope == other.slope && this.yIntercept == other.yIntercept);
        }
        
        public int hashCode() {
            return Objects.hash(this.slope, this.yIntercept);
        }
    }
}
ztan5362
  • 9
  • 1

2 Answers2

0

equals needs to be public boolean equals(Object other) to match the signature in Object.

Your equals method doesn't override the one that the code in HashMap is calling.

Usually an equals method looks like this:

@Override
public boolean equals(Object other) {
    if (other == this) {
        return true;
    }
    if (!(other instanceof Equation)) {
        return false;
    }
    // instanceof above also covers null
    Equation otherEquation = (Equation) other;
    return otherEquation.slope == this.slope
        && otherEquation.yIntercept == this.yIntercept;
}

...or use Project Lombok's @EqualsAndHashCode annotation.

Robert
  • 7,394
  • 40
  • 45
  • 64
0

If you want to overwrite a method annotade it with @Override. The compiler would give you an error for your equals because you do not overwrite but overload the method

@Override
public boolean equals(Object other) {
    ...
}
Stefan Warminski
  • 1,845
  • 1
  • 9
  • 18