Java映射和基元

我想创建一个映射,它将String作为键,将基元作为值。 我正在查看Java文档,并没有看到Primitive是一个类类型,或者他们共享某种包装类。

如何将值约束为原语?

Map map = new HashMap();

Java Autoboxing允许在Long, Integer, Double上创建映射,然后使用原始值操作它们。 例如:

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

如果要在一个地图中存储不同的基本类型,可以通过制作Map 。 允许存储BigDecimalBigIntegerByteDoubleFloatIntegerLongShort (和AtomicLongAtomicInteger )的值。

这是一个例子:

 Map map = new HashMap(); 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原始地图”,你会发现一些专门的类型,避免了自动装箱的需要。 例如: https : //labs.carrotsearch.com/hppc.html

但是,一般来说,如其他答案中所述,您应该使用自动装箱。

每个原语都有一个包装类,比如java.lang.Long

因此,您可以将包装类映射到String ,如果使用Java 1.5+,只需将基元放到地图中:

  Map map = new HashMap(); map.put("key", 10); int value = map.get("key"); // value is 10. 

您可以执行以下操作:

 Map map = new HashMap() 

那么操作就像:

 map.put("One", 1); 

将工作。 原语1将自动装入Integer 。 同样:

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

也将工作,因为Integer将自动取消装箱成一个int

查看有关自动装箱和自动装箱的一些文档。

你会使用他们的盒装对应物。

 Map map = new HashMap(); 

Integer是原始int的不可变盒装类型。 有类似的Short,Long,Double,Float和Byte盒装类型。

如果由于性能原因需要将值作为基元,则可以使用TObjectIntHashMap或类似的。

例如

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

Map 的一个不同之处在于值的类型是int primitive而不是Integer对象。

您不能在Map接口中将基元作为键或值。 相反,您可以使用Wrapper类,如IntegerCharacterBoolean等。

在维基上阅读更多内容。