java - 三元运算符与 Map NullPointerException Java
问题描述
这里的疑问是,如果地图中的键不存在,它会返回 null,而我正在尝试将其放入Integer
.
import java.util.*;
class Main {
public static void main(String[] args) {
HashMap<String,Integer> hm =new HashMap<>();
hm.put("abc",1);
hm.put("xyz",1);
System.out.println(hm.get("pqr"));
Integer result = hm !=null ? hm.get("pqr") : 0;
System.out.println(result);
}
}
输出:
null
Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:10)
如果我将三元运算符拆分为if-else
Like:
import java.util.*;
public class TestMain {
public static void main(String[] args) {
HashMap<String,Integer> hm =new HashMap<>();
hm.put("abc",1);
hm.put("xyz",1);
System.out.println(hm.get("pqr"));
Integer result;
if ( hm != null){
result = hm.get("pqr");
} else
result =0;
System.out.println(result);
}
}
输出:
null
null
三元运算符出了什么问题?
解决方案
三元条件表达式的类型
hm !=null ? hm.get("pqr") : 0
是int
,所以hm.get("pqr")
(其值为null
)被拆箱到int
,这会抛出NullPointerException
.
为了避免它,你可以写:
Integer result = hm !=null ? hm.get("pqr") : Integer.valueOf(0);
现在三元条件表达式的类型将是Integer
,因此不会尝试 unbox hm.get("pqr")
,也不例外。
确定三元条件运算符类型的逻辑可以在15.25 中找到。条件运算符 ? :在Table 15.25-A
和Table 15.25-C
。
推荐阅读
- android - 我的应用未显示清单文件中的名称
- html - 如何从 p 或 div 中抓取文本,输出给出一个空列表或无
- angular - Angular 应用程序中页脚后的额外空白
- amazon-web-services - 如何连接 AWS 账户
- native-base - 本机基础标签 - 知道如何删除标签周围的边框吗?
- react-native - Reactnative TypeError 中未显示特定页面的 Json 数据:
- r - R 中的 plotly 包如何从没有人脸信息的顶点信息创建实体 3D 网格
- php - 如何从指定文件夹中获取多个单独的旋转随机图像
- android - 在回收站视图中,如何确定单击的单选按钮来自 Android 中的同一个单选组
- .net-core - OData 日期过滤器返回损坏的 json