Search code examples
javahashmap

Incorrect value returned by IdentityHashMap - Why?


To my understanding, the following code should print false as it is doing identity based comparison.

However, when I run the following code it is printing true:

public class Test1 {
  public static void main(String[] args) {
    IdentityHashMap m = new IdentityHashMap();
    m.put("A", new String("B"));
    System.out.println(m.remove("A", new String("B")));
  }
}

Can some one help me understand why this behaving like this?


Solution

  • You have actually hit a bug in JDK, see JDK-8178355. IdentityHashMap does not have custom implementation of the remove(K,V) method added to Map via default method, which is causing this issue.