Java – HashMap means that even if it does exist, the key does not exist
I have an interesting problem. I'm sure it's HashMap's fault Consider the following debugging code (AMAP is the HashMap and 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 I insert a channel and value into this map Later, I tried to get the value with get () and run the debugging code. In my example, I gave 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, getting the key directly from the HashMap doesn't work, but the loop gets the exact same key through I, which means it can't find it in get() My question is what causes this? How can get() not find the existing key?
I'll provide some sample code, but I don't seem to be able to reproduce it independently
Any suggestions that might cause this problem?
Solution
From what I have seen, we still do not rule out whether it is related to invariance
aMap.put(key,value); key.setFieldIncludedInHashCodeAndEquals(25);
Then you'll get the results from it
To exclude this, show us more code or add it to the for loop in the example above
System.out.println(aMap.get(entry.getKey()));
In addition, use the debugger In this way, you can see whether your object is in the correct bucket