这段代码
public static int getValue(int key) {
return map.get(key);
}
private static Map<Integer, Integer> map;
static {
map = new HashMap<>();
map.put(1, 1);
map.put(2, 2);
}
Run Code Online (Sandbox Code Playgroud)
产生Lint警告
'map.get(key)' 的拆箱可能会产生 'NullPointerException'
可以通过检查以下内容来修复此警告null:
public static int getValue(int key) {
Integer n = map.get(key);
return n != null ? n : -42;
}
Run Code Online (Sandbox Code Playgroud)
有没有更好的办法?
从 Java 8 开始,您可以getOrDefault根据文档使用 :https : //docs.oracle.com/javase/8/docs/api/java/util/Map.html#getOrDefault-java.lang.Object-V-
| 归档时间: |
|
| 查看次数: |
1800 次 |
| 最近记录: |