I have the following class:
public static final Map<ChunkLoc,String> claims = new HashMap<>();
public final UUID world;
public final int x;
public final int z;
public static void main(String[] aefjpa) throws Throwable {
final UUID u = UUID.randomUUID();
final ChunkLoc c = new ChunkLoc(u, 123, -634);
claims.put(c, "apekop");
System.out.println(c.getOwner());
final ChunkLoc a = new ChunkLoc(u, 123, -634);
System.out.println(a.getOwner());
System.out.println(a.equals(c));
}
public ChunkLoc(final UUID world, final int x, final int z) {
this.world = world;
this.x = x;
this.z = z;
}
public String getOwner() {
return claims.get(this);
}
public boolean equals(final ChunkLoc chunk) {
return world.equals(chunk.world) && x == chunk.x && z == chunk.z;
}
public int hashCode() {
return x << z;
}
For some reason, the claims Map
is not working as expected. When I create a ChunkLoc to put a String in the map and then create another ChunkLoc with the same values to get the String back from the map, it returns null. The main() method outputs the following:
apekop
null
true
I thought a HashMap should be functioning differently when the hashCode is the same and equals() returns true. Why is it giving the above output?