Issue
I overrided the hashCode and equals method of a class. I also wrote unit tests for it and it's all green. When I tested it out with a hashmap, I noticed something weird. I created 2 identical objects:
obj1 = new PacmanVeld(field2);
obj2 = new PacmanVeld(field2);
I tested it out with this piece of code:
Assert.assertTrue(obj1.hashCode() == obj2.hashCode()); //works
Assert.assertTrue(obj1.equals(obj2)); //works
HashMap<PacmanVeld, Integer> testMap = new HashMap<>();
testMap.put(obj1, 5);
Assert.assertTrue(testMap.put(obj2, 7) == 5); //fails throws nullpointerexception
Assert.assertTrue(testMap.get(obj1) == 7); //fails
I don't understand why this won't work as I understand that in the algorithms of a HashMap, obj1 and obj2 are the same objects.
The PacmanVeld class:
public class PacmanVeld
{
private Node[][] nodes;
public PacmanVeld(char[][] veld)
{
this.nodes = new Node[veld.length][veld[0].length];
for (int i = 0; i < veld.length; i++)
{
for (int j = 0; j < veld[i].length; j++)
{
switch (veld[i][j])
{
case '%':
nodes[i][j] = new Node(i, j, NodeType.WALL);
break;
case ' ':
nodes[i][j] = new Node(i, j, NodeType.EMPTY);
break;
case '.':
nodes[i][j] = new Node(i, j, NodeType.CRUMB);
break;
case 'P':
nodes[i][j] = new Node(i, j, NodeType.PACMAN);
break;
}
}
}
initFinish();
initPacman();
}
//getters, setters & methods
public boolean equals(PacmanVeld p)
{
if (p.nodes.length != nodes.length) { return false; }
for (int i = 0; i < nodes.length; i++)
{
if (!Arrays.deepEquals(nodes[i], p.nodes[i])) { return false; }
}
return true;
}
@Override
public int hashCode()
{
List<Node> nodeList = getNodeList();
return Arrays.deepHashCode(nodeList.toArray());
}
private void initPacman()
{
for (Node[] rij : this.nodes)
{
for (Node n : rij)
{
if (n.isPacman())
{
pacman = n;
}
}
}
}
}
Solution
The problem is that you didn't override the equals()
method herited from the object class.
@Override
public boolean equals(Object o)
{
PacmanVeld p = (PacmanVeld)o;
if (p.nodes.length != nodes.length) { return false; }
for (int i = 0; i < nodes.length; i++)
{
if (!Arrays.deepEquals(nodes[i], p.nodes[i])) { return false; }
}
return true;
}
Answered By - Alexis C.