4

I have defined a Point class as shown below, overriding the equals() and hashCode(). I was expecting that in the main() method, "Key Found" will be printed, but it's not.

It was my understanding that Java uses the equals() and hashCode() to add or find objects in a HashMap. I am not sure what am I doing wrong here.

import java.util.*;

public class Point {
  int row = 0;
  int col = 0;

  public Point(int row, int col) {
    this.row = row;
    this.col = col;
  }

  public String toString() {
    return String.format("[%d, %d]", row, col);
  }

  public boolean equals(Point p) {
    return (this.row == p.row && this.col == p.col);
  }

  public int hashCode() {
    return 31 * this.row + this.col;
  }

  public static void main(String[] args) {
    HashMap<Point, Integer> memo = new HashMap<>();
    Point x = new Point(1, 2);
    Point y = new Point(1, 2);
    memo.put(x, 1);

    if (x.equals(y))
      System.out.println("x and y are equal");

    System.out.println("Hashcode x= " + x.hashCode() + " Hashcode y= " + 
                       y.hashCode());

    if (memo.containsKey(y)) {
      System.out.println("Key found");
    }
  }
}

output
x and y are equal
Hashcode x= 33 Hashcode y= 33
entpnerd
  • 10,049
  • 8
  • 47
  • 68
TanM
  • 99
  • 1
  • 6
  • 4
    Add `@Override` tags to your overriden methods and it gets quite clear what you did wrong. – Ben Jun 05 '18 at 07:09
  • do you understand why this method: public boolean equals(Point p) { return (this.row == p.row && this.col == p.col); } is not what/how you want (it) ? – Stultuske Jun 05 '18 at 07:09
  • Also, despite that you need to override Object#equals correctly, please have a look at the documentation for a correct equals implementation [here](https://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#equals(java.lang.Object)). If the other point is `null`, you will get a NullPointerException, altough `x.equals(null)` should return `false`. – Glains Jun 05 '18 at 11:56

1 Answers1

7

The problem is that you aren't actually overriding the equals() method. The equals() method that you are trying to override takes in an Object as a parameter, not a Point object. Therefore, the equals() method that you implemented isn't actually called.

entpnerd
  • 10,049
  • 8
  • 47
  • 68