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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With