Why is it possible to loop the keySet
of a TreeMap and getting a .containsKey == false
?
for (Object thisObject : map.keySet()) {
if (!map.containsKey(thisObject)) {
System.out.println("This line should be never reached.");
}
}
After a lot, lot of different iterations and calls this line gets hit. A map.get(thisObject)
would return null
.
But debug shows that the key (same reference, value and hash) and an actual value is in the map. The map is a small (25 elements) TreeMap<Long, Double>
UPDATE:
As guessed by @rgettman theres a custom sort Comparator
used at the construction of the TreeMap (Didn't see it because it was constructed from another class). This comparator was just (I guess) copy pasted from here
Changing the Comparator
:
public int compare(Object a, Object b) {
if((Double)base.get(a) > (Double)base.get(b)) {
return 1;
} else if((Double)base.get(a) == (Double)base.get(b)) {
return 0;
} else {
return -1;
}
}
to
...
} else if(base.get(a).equals(base.get(b))) {
return 0;
...
fixes the problem. The reason why this problem was showing up just after millions of operation was that there were no cases where the map had two similar values for two different keys, as this is very unlikely in the context.
So at:
25151l, 1.7583805400614032
24827l, 1.7583805400614032
it fails.
Thanks for your help!
You must have made changes to the backing entrySet()/Map.Entry
thereby changing the key orders, thereby having a failed search containsKey
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With