I've written a hashcode
function for this class and for some reason the hashmap is not properly recognizing when a key is actually present in the HashMap
. (coordinates is a string)
@Override
public int hashCode() {
return coordinates.hashCode();
}
And I've also written a .equals
method for the class that used to test whether two pairs of coordinates were equal to each other; However, to verify that my hashcode method is working correctly I've switched the .equals
method to the following.
public boolean equals(Object arg) {
Block a = (Block) arg;
return hashCode() == a.hashCode();
}
and they're all being called elsewhere with a hashmap.containskey()
call as follows:
return (hashblocks.containsKey(newz));
For some reason this only returns true ~ 50% of the time when it should (we even reinput the exact same case and sometimes it works sometimes it doesn't) I've had a lot of problem in the past trying to get contains methods to work properly for HashMap
s and Set
s and I'm wondering why this implementation in particular is having difficulty. (Basically, what could the bug possibly be)
3 1 3 1
true
4 2 4 2
false
0 0 1 0
0 3 1 3
2 0 3 0
2 3 3 3
0 1 1 2
2 1 2 2
4 0 4 0
4 2 4 2
3 1 3 1
3 2 3 2
3 1 3 1
true
4 2 4 2
true
3 2 3 2
true
0 0 1 0
0 3 1 3
2 0 3 0
3 3 4 3
0 1 1 2
2 1 2 2
4 0 4 0
4 2 4 2
3 1 3 1
3 2 3 2
the query is followed by its result and the long set of numbers represents all the keys followed by a newline char
to verify that my hashcode method is working correctly I've switched the .equals method to the following.
return hashCode()==a.hashCode();
This is going to work only in case of "perfect hashing", i.e. when equality of hash codes implies the equality of the actual values. Hash codes of String
in Java are not perfect (in fact, they cannot be perfect for all possible strings even theoretically).
You need to keep the equality check consistent with hash codes - in your case, that would be checking the equality of coordinates
:
public boolean equals(Object arg) {
Block a = (Block) arg;
return coordinates.equals(a.coordinates);
}