Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why java.util.Map value can be primitive array but not single primitive

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?

like image 299
Scavs Avatar asked Aug 12 '15 12:08

Scavs


1 Answers

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.

like image 141
Mage Xy Avatar answered Oct 10 '22 07:10

Mage Xy