HashMap get value of object that is "equal" but different hash?
According to the Java documentation,
If two objects are equal according to the
equals(Object)
method, then calling thehashCode
method on each of the two objects must produce the same integer result.
It appears that in your case two Point
objects are equal (as per the equals
method) but their hash codes are different. This means that you need to fix your equals
and hashCode
functions to be consistent with each other.
Can you try writing a self contained example like the follow we can run
Map<Point, String> map = new LinkedHashMap<>();
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++)
map.put(new Point(i, j), "(" + i + "," + j + ")");
// test the map
int misMatches = 0;
for (int i = 0; i < 10; i++)
for (int j = 0; j < 10; j++) {
String expected = "(" + i + "," + j + ")";
String text = map.get(new Point(i, j));
if (!expected.equals(text)) {
System.err.println("Expected <" + expected + "> but got <" + text + ">");
misMatches++;
}
}
System.out.println(misMatches + " mis-matches found.");
prints
0 mis-matches found.
I dont think there is any problem with equals() or hashcode() of Point class.Try this:
public static void main(String args[]) {
Map<Point, Integer> map = new HashMap<Point, Integer>();
Point p1 = new Point(0, 1);
Point p2 = new Point(0, 2);
map.put(p1,1);
map.put(p2,2);
Point p = new Point(0, 1);
if(p.equals(p1)){
System.out.println(map.get(p));
}
else{
System.out.println("not");
}
}
It is producing the correct result.
I guess you are not initialising the map properly.