Android Studio 發出警告: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}]
uj5u.com熱心網友回復:
假設沒有其他東西在修改地圖,并且如果地圖從不包含空值,這對我來說看起來是安全的 - 但是您可以通過無條件呼叫和使用結果來處理丟失的鍵來避免警告并同時提高效率get好:
Integer currentCount = idCollisionMap.get(currentId);
Integer newCount = currentCount == null ? 1 : currentCount 1;
idCollisionMap.put(newCount);
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/314955.html
標籤:爪哇 安卓 哈希图 android-lint
