HashMap says Key doesn't exist even if it

I had an interesting problem, and I'm sure this is a HashMap error. Consider the following debugging code (AMap is HashMap, key is the value passed to this method)

 System.out.println("getBValues - Given: " + key); System.out.println("getBValues - Contains Key: " + AMap.containsKey(key)); System.out.println("getBValues - Value: " + AMap.get(key)); for(Map.Entry<A,HashSet<B>> entry : AMap.entrySet()) { System.out.println("getBValues(key) - Equal: " + (key.equals(entry.getKey()))); System.out.println("getBValues(key) - HashCode Equal: "+(key.hashCode() == entry.getKey().hashCode())); System.out.println("getBValues(key) - Key: " + entry.getKey()); System.out.println("getBValues(key) - Value: " + entry.getValue()); } 

Now on this map I insert one key (Channel) and a value. Later, I will try to return the value using get() and run this debugging code, which in my case gives this output:

 getBValues - Given: Channel(...) getBValues - Contains Key: false <--- Doesnt contain key?! getBValues - Value: null <--- Null (bad) getBValues(key) - Equal: true <--- Given key and AMap key is equal getBValues(key) - HashCode Equal: true getBValues(key) - Key: Channel(Same...) getBValues(key) - Value: [] <--- Not null (This is the expected result) 

As you can see, fetching from HashMap does not work directly, but through the loop I get the same key, that is, it simply cannot be found there using get() . My question is what might cause this? How to get() not find a key that exists?

I would provide some sample code, but I cannot reproduce this myself.

Any suggestions on what could be causing this?

+6
source share
2 answers

From what I see, we still do not exclude whether this is due to immutability. If you do:

 aMap.put(key, value); key.setFieldIncludedInHashCodeAndEquals(25); 

then you will get the result from above.

To eliminate this, either show us more of your code, or in the for loop in the above example add

 System.out.println(aMap.get(entry.getKey())); 

Also use a debugger. This way you can see if your object is in the right bucket.

+4
source

I bet you didn't override equals and hashCode correctly in your Channel key class. That would explain it.

Joshua Bloch tells you how to do it right in Chapter 3, Effective Java.

http://java.sun.com/developer/Books/effectivejava/Chapter3.pdf

+8
source

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


All Articles