Note that there are some explanatory texts on larger screens.

plurals
  1. POChecking for and Removing elements in Java HashMap
    text
    copied!<p>I am trying to check for and remove elements, using a HashMap in Java. Its keys are a type I created called ClusterKey, and its values are a type I created called ClusterValue.</p> <p>Here is the code that is causing issues:</p> <pre><code>ClusterKey ck = new ClusterKey(Long.parseLong(split[0].split("=")[1]), Integer.parseInt(split[1].split("ey")[1])); if (arg == 0) keys.put(ck, new ClusterValue(index, false)); if (arg == 1) { if (keys.containsKey(ck)) { index = keys.get(ck).messageNo; keys.remove(ck); } keys.put(ck, new ClusterValue(index, true)); } </code></pre> <p>The problem is that even when the ClusterKey is the same as an existing ClusterKey, containsKey() and remove() do not seem to recognize it as equal. I have implemented equals() in class ClusterKey to override Java's equals() method, as follows:</p> <pre><code>class ClusterKey { long firstKey; int secondKey; public ClusterKey(long firstKey, int secondKey) { this.firstKey = firstKey; this.secondKey = secondKey; } public boolean equals(Object otherKey) { return this.firstKey == ((ClusterKey) otherKey).firstKey &amp;&amp; this.secondKey == ((ClusterKey) otherKey).secondKey; } } </code></pre> <p>So, I'm quite confused. Thanks so much for your help.</p> <p>Regards, Rebecca</p> <p>UPDATE: Thank you for your advice and feedback on my code. I was able to solve the problem by adding hashCode() to ClusterKey, as follows:</p> <pre><code> } public boolean equals(Object otherKey) { return this.firstKey == ((ClusterKey) otherKey).firstKey &amp;&amp; this.secondKey == ((ClusterKey) otherKey).secondKey; } public int hashCode() { return (int) firstKey + secondKey; } </code></pre>
 

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