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条回答
叛逆
2楼-- · 2019-04-26 20:59

If you need the value to be a primitive for performance reasons, you can use TObjectIntHashMap or similar.

e.g.

TObjectIntHashMap<String> map = new TObjectIntHashMap();

map.put("key", 10);
int value = map.get("key");

One difference with Map<String, Integer> is that the values are of type int primitive rather than Integer object.

查看更多
登录 后发表回答