Java映射和原语 [英] Java Mappings and Primitives
问题描述
我想创建一个映射,它将一个 String
作为键,而原语作为值。我正在查看Java文档,并没有看到Primitive是一个类类型,或者他们分享了一些类包装类。
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 允许在上创建地图,整数,双重
,然后使用原始值操作它们。例如:
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
如果要存储在一个地图上原始类型,你可以通过做一个 Map< String,Number>
来实现。允许存储 BigDecimal
, BigInteger
,字节
的值, Double
, Float
,整数
,长
, Short
(和 AtomicLong
, AtomicInteger
)。
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
).
以下是一个示例:
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);
}
这篇关于Java映射和原语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!