Map<String,Integer> map = new HashMap<String,Integer>(); if(map == null){ System.out.println("map is null"); }else{ Integer a = map.get(""); System.out.println(a); }这段代码输出nullMap<String,Integer> map = new HashMap<String,Integer>(); if(map == null){ System.out.println("map is null"); }else{ int a = map.get(""); System.out.println(a); }这段代码报错:Exception in thread "main" java.lang.NullPointerException at Test.main(Test.java:11)
at Show.main(Show.java:12)
出乎意料
你去key之前,不判断map中有没有这个key吗?
Map<String,Integer> map = new HashMap<String,Integer>();
if(map == null){
System.out.println("map is null");
}else{
Integer a = map.get("");
System.out.println(a);
}这段代码输出nullMap<String,Integer> map = new HashMap<String,Integer>();
if(map == null){
System.out.println("map is null");
}else{
int a = map.get("");
System.out.println(a);
}这段代码报错:Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:11)
1.int要改成Integer的,因为要跟map中的value值类型相匹配
2.map判断是否为空不是用==null判断的,map在new出来之后本身就相当于一个容器,只是里面没装东西而已,而且map有判断是否为空的方法:isEmpty()
map.get("")此句得到的值为null
再将null 转为int的过程时报出的空指针