【发布时间】:2023-03-12 02:10:01
【问题描述】:
这里的疑问是,如果地图中的键不存在,它会返回 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 喜欢:
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
三元运算符出了什么问题?
【问题讨论】:
标签: java nullpointerexception hashmap integer conditional-operator