奇怪的 EnumMap 行为

Strange EnumMap behavior

我尝试使用简单的 java EnumMap 来存储道路类型到默认速度的映射。但是我 运行 立即陷入以下问题:

我创建了一个简单的枚举如下:

   public enum RoadCategory {

        AUTOBAHN("Autobahn", 0),
        BUNDESSTR("Bundesstrasse", 1),
        OTHER("other", -1);

        private String name;
        private int code;

        private RoadCategory(String name, int code){
            this.name = name;
            this.code = code;
        }
    }

接下来我创建了一个小的 class 并试图将此枚举用作枚举映射的键:

import java.util.EnumMap;
import java.util.Map;

public class VehicleConfig {

    public static void main(String[] args) throws Exception {
        VehicleConfig v = new VehicleConfig();
        v.addSpeedMapping(RoadCategory.AUTOBAHN, 80.0);
    }

    private Map<RoadCategory,Double> speedMap;

    public VehicleConfig(){
        this.speedMap = new EnumMap<RoadCategory, Double>(RoadCategory.class);
    }

    public double addSpeedMapping(RoadCategory category, double speed) throws Exception{
        if(speedMap == null) throw new Exception("speedmap NULL");
        if(category == null) throw new Exception("category NULL");
        return this.speedMap.put(category, speed);  // this is line 20
    }
}

不幸的是,addSpeedMapping 在行 return this.speedMap.put(category, speed); 中抛出了一个 NullPointerException。因此我添加了条件,但这对这里没有帮助。

Exception in thread "main" java.lang.NullPointerException
    at hpi.bpt.traffic.VehicleConfig.addSpeedMapping(VehicleConfig.java:20)
    at hpi.bpt.traffic.VehicleConfig.main(VehicleConfig.java:8)

我不知道我做错了什么。有人知道如何得到这个 fixed/working 吗?

documentation

the previous value associated with key, or null if there was no mapping for key. (A null return can also indicate that the map previously associated null with key, if the implementation supports null values.)

this.speedMap.put(category, speed); 将 return 如果地图中没有您的 category 的键。

现在 java 将尝试将 null 转换为 double(这意味着 java 调用了 null.doubleValue()),这将抛出一个NPE.