Home > other >  Unboxing may produce Null Pointer Exception after checking if key exists in Map
Unboxing may produce Null Pointer Exception after checking if key exists in Map

Time:10-15

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}]

CodePudding user response:

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);
  • Related