Here are two examples
Map value as Single value
private Map<Short, Boolean> _Booleans = new HashMap<Short, Boolean>(); //works
private Map<Short, boolean> _Booleans = new HashMap<Short, boolean>(); //not allowed
Map value as Array
private Map<Short, Boolean[]> _Booleans = new HashMap<Short, Boolean[]>(); //works
private Map<Short, boolean[]> _Booleans = new HashMap<Short, boolean[]>(); //works!
Primitive wrappers are forced on single value, but primitive arrays are allowed, why is that?
Sub question: Is it possible to use single value primitives with a Map?
Maps can only store Objects
. Primitives are not Objects
unless they are in a wrapper class (Boolean
instead of boolean
in your example).
Arrays are always Objects
, regardless of what kind of data they contain. Therefore, they can be stored in a Map without any problems.
In Java, typically you should prefer using primitive values, as they are faster and smaller in regards to memory usage. However, there are some cases (like the one in your example) where the boxed type is more useful. In some cases (typically when using generics), autoboxing might take effect.
An important difference between a primitive and its Object
counterpart is that the Object
can be null. A primitive is NEVER null.