Note that there are some explanatory texts on larger screens.

plurals
  1. POJava Hashmap two identical objects stored seperate
    primarykey
    data
    text
    <p>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:</p> <pre><code>obj1 = new PacmanVeld(field2); obj2 = new PacmanVeld(field2); </code></pre> <p>I tested it out with this piece of code:</p> <pre><code>Assert.assertTrue(obj1.hashCode() == obj2.hashCode()); //works Assert.assertTrue(obj1.equals(obj2)); //works HashMap&lt;PacmanVeld, Integer&gt; testMap = new HashMap&lt;&gt;(); testMap.put(obj1, 5); Assert.assertTrue(testMap.put(obj2, 7) == 5); //fails throws nullpointerexception Assert.assertTrue(testMap.get(obj1) == 7); //fails </code></pre> <p>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.</p> <p>The PacmanVeld class:</p> <pre><code>public class PacmanVeld { private Node[][] nodes; public PacmanVeld(char[][] veld) { this.nodes = new Node[veld.length][veld[0].length]; for (int i = 0; i &lt; veld.length; i++) { for (int j = 0; j &lt; 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 &amp; methods public boolean equals(PacmanVeld p) { if (p.nodes.length != nodes.length) { return false; } for (int i = 0; i &lt; nodes.length; i++) { if (!Arrays.deepEquals(nodes[i], p.nodes[i])) { return false; } } return true; } @Override public int hashCode() { List&lt;Node&gt; nodeList = getNodeList(); return Arrays.deepHashCode(nodeList.toArray()); } private void initPacman() { for (Node[] rij : this.nodes) { for (Node n : rij) { if (n.isPacman()) { pacman = n; } } } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload