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/