Android给出了警告:Unboxing of 'idCollisonMap.get(currentId)' may produce 'NullPointerException',即使在执行Map.get()之前,我正在检查键是否存在。
,我真的有遇到空指针异常的危险吗?我的理解是,.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);
}
}
}代码片段示例输出:
[{T143=1, T153=3, T141=1}]
发布于 2021-10-14 16:31:52
假设没有修改映射,而且如果映射从未包含空值,那么在我看来这是安全的--但您可以避免警告,同时通过无条件调用get并使用结果来处理丢失的键,从而提高效率:
Integer currentCount = idCollisionMap.get(currentId);
Integer newCount = currentCount == null ? 1 : currentCount + 1;
idCollisionMap.put(newCount);https://stackoverflow.com/questions/69574185
复制相似问题