Validate and delete items in Java HashMap

I am trying to check and delete items using a HashMap in Java. Its keys are type I created under the name ClusterKey, and its values ​​are type I created under the name ClusterValue.

Here is the code causing the problems:

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)); } 

The problem is that even if ClusterKey matches the existing ClusterKey, containsKey () and remove () do not seem to recognize it equal. I applied equals () in the ClusterKey class to override the Java equals () method as follows:

 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 && this.secondKey == ((ClusterKey) otherKey).secondKey; } } 

So, I am very confused. Thank you very much for your help.

Regards, Rebecca

UPDATE: Thanks for your tips and feedback on my code. I was able to solve the problem by adding hashCode () to ClusterKey as follows:

  } public boolean equals(Object otherKey) { return this.firstKey == ((ClusterKey) otherKey).firstKey && this.secondKey == ((ClusterKey) otherKey).secondKey; } public int hashCode() { return (int) firstKey + secondKey; } 
+2
source share
2 answers

For any operation of a data structure that supports Hash (for example, HashMap , HashSet ), its elements must override hashCode() in addition to the equals() method. The reason is that the hash code is used to identify the bucket into which to place the element (during insertion) or to perform a search (using equals() during the search).

If you do not override hashCode() , the default implementation from Object#hashCode() , which will return different values ​​even for objects that you consider equivalent (the equals() method returns true).

That's why your

  hashMap.containsKey(ClusterKey key) 

calls fail despite the presence of an already present key. Since the hash codes do not match the HashMap , it never searches for a key in the right bucket. Therefore, your equals() will never be called here.

+3
source

You will need to implement hashCode() , not just equals , so that your ClusterKey works well as a key in the HashMap .

In particular, quoting from related Javadocs:

If two objects are equal according to the equals (Object) method, then calling the hashCode method on each of the two objects should have the same integer result.

+3
source

Source: https://habr.com/ru/post/1498698/


All Articles