Java Mappings and Primitives

2019-04-26 20:18发布

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>();

7条回答
Lonely孤独者°
2楼-- · 2019-04-26 20:46

Java Autoboxing allows to create maps on Long, Integer, Double and then operate them using primitive values. For example:

java.util.HashMap<String, Integer> map = new java.util.HashMap<String, Integer>();
map.put("one", 1); // 1 is an integer, not an instance of Integer

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 of BigDecimal, BigInteger, Byte, Double, Float, Integer, Long, Short (and AtomicLong, AtomicInteger).

Here is an example:

Map<String, Number> map = new HashMap<String, Number>();

map.put("one", 1);
map.put("two", 2.0);
map.put("three", 1L);

for(String k:map.keySet()) {
  Number v = map.get(k);
  System.err.println(v + " is instance of " + v.getClass().getName() + ": " + v);
}
查看更多
甜甜的少女心
3楼-- · 2019-04-26 20:47

You can do the following:

Map<String, Integer> map = new HashMap<String, Integer>()

Then operations like:

map.put("One", 1);

will work. The primitive 1 will get auto-boxed into an Integer. Likewise:

int i = map.get("One");

will also work because the Integer will get auto-unboxed into an int.

Check out some documentation on autoboxing and autounboxing.

查看更多
仙女界的扛把子
4楼-- · 2019-04-26 20:51

You would use their boxed counterpart.

Map<String,Integer> map = new HashMap<String,Integer>();

Integer is an immutable boxed type of the primitive int. There are similar Short, Long, Double, Float and Byte boxed types.

查看更多
姐就是有狂的资本
5楼-- · 2019-04-26 20:54

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.

查看更多
来,给爷笑一个
6楼-- · 2019-04-26 20:54

You can't have a primitive as key or value in Map interface. Instead you can use Wrapper classes, like Integer, Character, Boolean and so on.

Read more on wiki.

查看更多
一夜七次
7楼-- · 2019-04-26 20:56

Every primitive has a wrapper class, like java.lang.Long for long.

So you can map the the wrapper class to Stringand, if you use Java 1.5+, simply put primitives to the map:

 Map<String, Integer> map = new HashMap<String, Integer>();
 map.put("key", 10);
 int value = map.get("key");  // value is 10.
查看更多
登录 后发表回答