java - 检查 Map 中是否存在键后,拆箱可能会产生空指针异常

标签 java android hashmap android-lint

Android Studio 发出警告:Unboxing of 'idCollisonMap.get(currentId)' may produce 'NullPointerException' 即使我在执行 Map.get() 之前检查 key 是否存在。
我真的有遇到空指针异常的危险吗?我的理解是.containsKey()检查将防止这种情况发生。

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);
        }
    }
}
代码 fragment 示例输出:[{T143=1, T153=3, T141=1}]

最佳答案

假设没有其他任何东西正在修改 map ,并且如果 map 从不包含空值,这对我来说看起来很安全 - 但您可以通过无条件调用 get 来避免警告并同时提高效率并使用结果来处理丢失的键:

Integer currentCount = idCollisionMap.get(currentId);
Integer newCount = currentCount == null ? 1 : currentCount + 1;
idCollisionMap.put(newCount);

关于java - 检查 Map 中是否存在键后,拆箱可能会产生空指针异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69574185/

相关文章:

java - 具有多种条件的可比接口(interface)

java - 在 Netbeans 中使用文件过滤器

ruby - 对散列中的值求和

java - 在使用 JNI 将 c++ unordered_map 返回到 java 之前将其转换为 java hashMap

java - java中如何拒绝空格作为输入

java - 由于更改包名称而出错

java - 错误 :Execution failed for task ':app:processDebugManifest' . list 合并因多个错误而失败,请参阅日志

java - 删除月份 SimpleDateFormat 中的前导 "0"

android - 当应用程序在后台被杀死且设备被锁定时,警报管理器将无法工作

android - 无法从 View 转换为相对布局