// Explicit unboxing
int x = (int) (Integer) map.get("int");
// Implicit unboxing
int y = (Integer) map.get("int");
// USing a method from Number instead
int z = ((Integer) map.get("int")).intValue();
# 4 楼答案
当您将原语放入Java中的Map中时,它们将自动装箱到对象形式中。例如,如果将Map定义为:
Map<Integer, String> myMap = new HashMap<Integer, String>();
然后您可以使用int类型的原语,因为它们将自动装箱到Integer中
至于你最初的问题,将Map定义为:
// using Integer for key type, can be something else
Map<Integer, Object> myMap = new HashMap<Integer, Object>();
# 1 楼答案
您可以使用
Integer
而不是int
# 2 楼答案
您可以利用自动装箱并使用
Integer
而不是int等等相应的类型(
Integer
,Double
,Bool
,…)继承对象,这样您就可以使用标准的Map<Object, Whatever>
并向它抛出任意内容# 3 楼答案
听起来你只是想要一个
Map<String, Object>
(或者任何你的键类型)基本值将被适当地装箱:
请注意,为了检索值并unbox它,您必须提到特定的包装器类型:
# 4 楼答案
当您将原语放入Java中的
Map
中时,它们将自动装箱到对象形式中。例如,如果将Map
定义为:然后您可以使用
int
类型的原语,因为它们将自动装箱到Integer
中至于你最初的问题,将
Map
定义为:然后,您应该能够在映射中放置任何Java对象