I want to create a mapping that takes a String
as the key and a primitive as the value. I was looking at the Java docs and did not see that Primitive was a class type, or that they shared some kind of wrapping class.
How can I constrain the value to be a primitive?
Map<String, Primitive> map = new HashMap<String, Primitive>();
Java Autoboxing allows to create maps on
Long, Integer, Double
and then operate them using primitive values. For example:If you want to store in one map different primitive types, you can to it by making a
Map<String, Number>
. Allows to store values ofBigDecimal
,BigInteger
,Byte
,Double
,Float
,Integer
,Long
,Short
(andAtomicLong
,AtomicInteger
).Here is an example:
You can do the following:
Then operations like:
will work. The primitive
1
will get auto-boxed into anInteger
. Likewise:will also work because the
Integer
will get auto-unboxed into anint
.Check out some documentation on autoboxing and autounboxing.
You would use their boxed counterpart.
Integer is an immutable boxed type of the primitive int. There are similar Short, Long, Double, Float and Byte boxed types.
Google for "Java Primitive Maps" and you will find some specialised types which avoid the need for autoboxing. An example of this is: https://labs.carrotsearch.com/hppc.html
However, in general you should do fine with autoboxing as mentioned in other answers.
You can't have a primitive as key or value in
Map
interface. Instead you can use Wrapper classes, likeInteger
,Character
,Boolean
and so on.Read more on wiki.
Every primitive has a wrapper class, like
java.lang.Long
forlong
.So you can map the the wrapper class to
String
and, if you use Java 1.5+, simply put primitives to the map: