Search code examples
javaenumsenum-map

Strange EnumMap behavior


I tried to use a simple java EnumMap to store a mapping of road types to default speeds. But immediately I ran into the following problem:

I created a simple enum as follows:

   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;
        }
    }

Next I created a small class an tried to use this enum as key of an enum map:

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
    }
}

Unfortunately the addSpeedMapping throws a NullPointerException in the line return this.speedMap.put(category, speed);. Therefore I added the conditionals, but that didn't help here.

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)

I've no idea what I'm doing wrong here. Does anybody know how to get this fixed/working?


Solution

  • See the 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); will return null if no key for your category is in the map.

    and now java will try to convert null to a double (that means java called null.doubleValue()) and this will throw an NPE.