Video in progress

Senior ☕ Core Java

get(id) on a Map<Long, User> always returns null, but the entry is definitely in the map. What wrapper-type and equals trap could this be?

Map<Long, User> users = loadUsers();   // the keys are Long
int id = request.userId();
User u = users.get(id);                 // ?

The parameter of Map.get is Object, not generic. An int id is silently boxed to Integer, and Integer.equals(Long) is always false, even when the values are equal. The compiler gives no error; only the IDE or Error Prone warns.

📖 Answer

null. users.get(id) becomes users.get(Integer.valueOf(id)). HashMap does find the right bucket by hash (Long.hashCode(42) == Integer.hashCode(42)), but then Integer.valueOf(42).equals(42L) is false, because Integer.equals only accepts an Integer.

Why get(Object) and not get(K)? When generics were added in Java 5, get, containsKey, remove and contains stayed accepting Object for compatibility with old code. That's why the compiler doesn't catch this kind of mistake.

Other cases from the same family:

Set<Short> set = new HashSet<>();
for (short i = 0; i < 100; i++) {
    set.add(i);
    set.remove(i - 1);   // i - 1 is an int, becomes an Integer, nothing gets removed
}
set.size();              // 100

new BigDecimal("42").equals(42L);       // false
Long.valueOf(42).equals(42);            // false

The worst variant in prod is dynamic data. When Jackson reads into a Map<String, Object>, it makes a small number an Integer and a large one a Long. Code with payload.get("userId").equals(user.getId()) gives one result for the small ids in tests and another for the large ids in prod. The same goes for values that come through Redis or a cache.

What I do:

  • normalize the type at the boundary: ((Number) v).longValue(), or bind straight into a typed DTO;
  • wrap ids in their own type: record UserId(long value), so you can't pass an int to a Map<UserId, User>;
  • turn on Error Prone's CollectionIncompatibleType check: it turns Map<Long,…>.get(Integer) into a compile error. IntelliJ also shows "Suspicious collection method call": don't switch that warning off.