This rule raises an issue when an IdentityHashMap is created with a boxed primitive type as its key type.

Why is this an issue?

IdentityHashMap compares keys by reference instead of calling equals(). Boxed primitive types represent values as objects, but boxing the same primitive value more than once does not always return the same object. For example, some Integer values are cached while others may be represented by distinct instances.

Consequently, an IdentityHashMap with boxed primitive keys can appear to work for some values and fail for others. A lookup can return null even when the map contains a key with the same primitive value.

How to fix it

Use a map implementation that compares keys by value when the key represents a primitive value. If reference equality is required, use key objects whose identity is deliberate and stable.

Code examples

Noncompliant code example

Map<Integer, UserSession> sessions = new IdentityHashMap<>(); // Noncompliant

sessions.put(500, session);
UserSession retrieved = sessions.get(500); // May return null

Compliant solution

Map<Integer, UserSession> sessions = new HashMap<>();

sessions.put(500, session);
UserSession retrieved = sessions.get(500);

Resources

Documentation