Why does the following code return null?
System.out.println("--------------");
HashMap<Coordinates, Cell> data = new HashMap<Coordinates, Cell>();
data.put(new Coordinates(0, 0), new Cell(tile));
System.out.println(boardData.get(new Coordinates(0, 0)));
// Debug script below
data.entrySet().forEach(entry -> {
System.out.println(entry.getKey() + " " + entry.getValue().peek().type());
});
System.out.println("--------------");
Output:
--------------
null
(0,0) QUEEN_BEE
--------------
The value is in the hashmap however I am not able to read anything from that location. Could anyone point out to me why this won’t work?
EDIT:
HashCode inside of Coordinates:
@Override
public int hashCode() {
return Objects.hash(q, r);
}
>Solution :
It seems you have not override hashcode and equals method in the Coordinates class.
You need to override hashcode and equals method to maintain the uniqueness between the objects.