Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does this java hashmap return null?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading