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