有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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) 个答案

  1. # 1 楼答案

    需要两个空检查来防止NPE,但是在这两种情况下都可以通过^{}方法解决

    此外,应该简化year的类型和赋值^仅当balance.getYear()返回字符串值时才需要{},否则可以将其作为Integer year = balance.getYear();

    for (AnnualLeaveBalance balance: annualLeaveBalanceList) {
        Map<Integer, Integer> yearToCountMap = employeeYearWiseLeaveAppCount.getOrDefault(
            balance.getEmployeeId(), Collections.emptyMap()
        ); // empty map is returned if no yearToCount map is found for a user
    
        Integer year = balance.getYear();
        int takenLeave = yearToCountMap.getOrDefault(year, 0); // no leave taken
    }