10

Android Studio gives the warning: Unboxing of 'idCollisonMap.get(currentId)' may produce 'NullPointerException' even though I am checking if the key exists before I perform the Map.get().

Am I actually in danger of running into a null pointer exception? My understanding is that .containsKey() check would prevent this from happening.

Map<String, Integer> idCollisonMap = new HashMap<>();

// All IDs to map
for (MyObject object : objectsWithIdList) {

    // Use the id as the key
    String currentId = object.getId();

    // First check if the ID is null
    if (currentId != null) {
        if (idCollisonMap.containsKey(currentId)) {
            // This ID already exists in the map,  increment value by 1
            idCollisonMap.put(currentId, idCollisonMap.get(currentId) + 1);
        } else {
            // This is a new ID,  create a new entry in the map
            idCollisonMap.put(currentId, 1);
        }
    }
}

Code snippet sample output:

[{T143=1, T153=3, T141=1}]

Kenny Sexton
  • 301
  • 4
  • 14
  • 1
    Well ... `containsKey` checks whether the _key_ exists (i.e. it is not null). But the `get` method gets you the _value_, which still might be null. – Seelenvirtuose Oct 14 '21 at 16:31

1 Answers1

9

Assuming nothing else is modifying the map, and if the map never contains null values, this looks safe to me - but you can avoid the warning and be more efficient at the same time, by unconditionally calling get and using the result to handle missing keys as well:

Integer currentCount = idCollisionMap.get(currentId);
Integer newCount = currentCount == null ? 1 : currentCount + 1;
idCollisionMap.put(newCount);
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194