Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java TreeMap contains a key but a containsKey call returns false (even the key is exactly the same unchanged object)

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!

like image 415
F___ThisToxicCommunityHere Avatar asked Nov 24 '22 17:11

F___ThisToxicCommunityHere


1 Answers

You must have made changes to the backing entrySet()/Map.Entry thereby changing the key orders, thereby having a failed search containsKey.

like image 127
Joop Eggen Avatar answered Dec 18 '22 16:12

Joop Eggen