public static void main(String[] args) {
Map<String,Object> hashResult= new HashMap<>();
try{
if(hashResult==null){
System.out.println("hashResult is null");
}
else {
System.out.println("hashResult is null can not recognise");
}
if(hashResult.isEmpty()){
System.out.println("hashResult is empty");
}
else {
System.out.println("hashResult isEmpty can not recognise");
}
if(hashResult.get("testKey")==null){
System.out.println("hashResult.testKey is null");
}
}catch (Exception e){
e.printStackTrace();
}
Map<String,Object> result= null;
try {
if (result == null) {
System.out.println("result is null");
} else {
System.out.println("result is null can not recognise");
}
if(result.get("testKey")==null){
System.out.println("result.testKey is null");
}
if (result.isEmpty()) {
System.out.println("result is empty");
} else {
System.out.println("result isEmpty can not recognise");
}
}catch (Exception e){
e.printStackTrace();
}
}
输出:
java.lang.NullPointerException
hashResult is null can not recognise
hashResult is empty
hashResult.testKey is null
result is null
at cn.utrust.fintech.p2passet.service.impl.PartnerAssetWeCashServiceImpl.main(PartnerAssetWeCashServiceImpl.java:646)
map可初始化为null 或new HashMap<>(),其中前者为空Object,只有Object 的特性,不能使用map相关方法及特性,result.get("testKey")==null 、result.isEmpty() 均会抛出异常;后者为空map, 不能用“==null”判空,可用map的isEmpty 方法,get不存在的key不会抛异常 。
map 判空:creditMap!=null&&!creditMap.isEmpty()