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!
I just executed the code, this case did return true to me.
Can you please give us the data that you input in the TreeMap. Thanks
This is the containKey(Object key) implementation from JavaDocs
Parameters:
Hope that helps.