java通过一个有效的键访问Map的Map给出了NPE
我有一张地图:
Map<Long, Map<Integer, Integer>> employeeYearWiseLeaveAppCount=new HashMap<>();
此地图在其他位置填充了值。现在,我需要像这样访问内部地图:
for (AnnualLeaveBalance balance: annualLeaveBalanceList) {
Map<Integer, Integer> yearToCountMap = employeeYearWiseLeaveAppCount.get(
balance.getEmployeeId()
);
int year = Integer.valueOf(balance.getYear());
int takenLeave = yearToCountMap.get(year); //year is valid value. NPE here!
}
我传递给此映射的键employeeYearWiseLeaveAppCount.get(balance.getEmployeeId());
在映射中确实存在,但yearToCountMap
显示为null。
请帮帮我这里怎么了
# 1 楼答案
需要两个空检查来防止NPE,但是在这两种情况下都可以通过^{} 方法解决
此外,应该简化},否则可以将其作为
year
的类型和赋值^仅当balance.getYear()
返回字符串值时才需要{Integer year = balance.getYear();