HashMap
does not take primitive types for the key and value, but we can still store values of primitive types easily as follows:
HashMap h = new HashMap();
h.put(1,1);
How is it possible?
HashMap
does not take primitive types for the key and value, but we can still store values of primitive types easily as follows:
HashMap h = new HashMap();
h.put(1,1);
How is it possible?
When you store primitives in a HashMap
(or any Collection
), they are boxed into their reference types. An int
is boxed to an Integer
.
That is because 1
is autoboxed to an Integer
(actually the same as this: Integer.valueOf(1)
). Find more info about autoboxing here.
int
is boxed to Integer
long
is boxed to Long
double
is boxed to Double
float
is boxed to Float
boolean
is boxed to Boolean
In your example you are using the raw type of the Map
. The Map
-object that you declared should most likely be declared like this:
Map<Integer, Integer> h = new HashMap<>();
h.put(1, 1);
Read more about raw types in this SO-question.
Primitives are autoboxed by the compiler and inserted as a wrapper object. So in your case it will be automatically boxed as Integer object. See this for details. Every primitive type has corresponding wrapper object with some of them like:
primitive - Object
byte - Byte
char - Character
short - Short
int - Integer
long - Long
double - Double
float - Float
boolean - Boolean
As any Java programmer knows, you can't put an int (or other primitive value) into a collection.
Collections can only hold object references, so you have to box primitive values into the appropriate wrapper class (which is Integer in the case of int).
When you take the object out of the collection, you get the Integer that you put in; if you need an int, you must unbox the Integer using the intValue method. All of this boxing and unboxing is a pain, and clutters up your code.
The autoboxing and unboxing feature automates the process, eliminating the pain and the clutter.