EnumMap raise NullPointerException

enum-map, java, nullpointerexception

Solution

The problem is the way you're using the return value of `put`, which is documented as:

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

The first time you call the `set` method for any particular key, the return value will be `null` - but you're then unboxing it to `byte`, which will throw the exception you're seeing.

Assuming you want to return the previous value, just change the return type to `Byte` for each method.

Problem

I've got a Enum and an `EnumMap<Parameters, Byte>`. I put the map into a class to hide the "byte" values. So I have a `set(Parameter, int)` and `set(Parameter, boolean)` method. ``` public enum Parameter { BLAH } public class Parameters { private final Map<Parameter, Byte> parameters = new EnumMap<>(Parameter.class); public byte set(Parameter parameter, boolean set) { return this.parameters.put(parameter, (byte) (set ? 0x01 : 0x00)); } public byte set(Parameter parameter, int value) { return this.parameters.put(parameter, (byte) value); } } ``` When I call any of my methods a NPW will raise which point to `put`! If I made the `parameters` public and call the method dircetly it works. ``` final Parameters parameters = new Parameters(); //parameters.parameters.put(Parameter.BLAH, (byte) 0x00); parameters.set(Parameter.BLAH, false); // NPE ``` Can anybody explain me the is behaviour to me?

Original source