Why the value of java.util.Map can be a primitive array, but not the only primitive

Here are two examples.

Map value as a 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 an array

 private Map<Short, Boolean[]> _Booleans = new HashMap<Short, Boolean[]>(); //works private Map<Short, boolean[]> _Booleans = new HashMap<Short, boolean[]>(); //works! 

Primitive shells are forced to one value, but primitive arrays are allowed, why?

Sub point: is it possible to use single primitives with a map?

+5
source share
2 answers

Maps can only store Objects . Primitives are not Objects unless they are in a shell class ( Boolean instead of Boolean in your example).

Arrays are always Objects , no matter what data they contain. Therefore, they can be stored on the card without any problems.

In Java, primitive values ​​are generally recommended as they are faster and smaller in terms of memory usage. However, there are some cases (for example, in your example) where the boxed type is more useful. In some cases (usually when using generics) autoboxing may take effect.

An important difference between a primitive and its Object is that Object can be null. The primitive NEVER matters.

+5
source

as @Nik means that only objects are stored in Map (any class in Java)

Now for your question, why an array of primitive Booleans can be saved -> this is because in Java (and many other languages) Array is Object

 boolean cc[]={true, false}; System.out.println(cc instanceof Object);//gives true 

Note β†’ this is true only because cc has an actual array in it, but if you put zero in it β†’ it will no longer be an instance of Object like this:

 cc=null; System.out.println(cc instanceof Object);//gives false 

Note 2 -> for your subtext: you cannot use them directly. Consider this example:

 HashMap aMap=new HashMap(); int x=120;//int value of 120 aMap.put("120",x);//parsed Integer with value of 120 x=aMap.get("120");//compiler error - Type mismatch 

One more thing, since you are interesting in this topic. I would suggest you a book called "Effective Java" by Joshua Bloch, who, by the way, developed the Java Collections, and Map is, of course, a collection.

+1
source

All Articles