java: HashMap<String, int> 不起作用

2022-08-31 07:58:00

HashMap<String, int>似乎不起作用,但确实有效。任何想法为什么?HashMap<String, Integer>


答案 1

在 Java 中,不能使用基元类型作为泛型参数。请改用:

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

使用自动装箱/取消装箱,代码几乎没有区别。自动装箱意味着您可以编写:

myMap.put("foo", 3);

而不是:

myMap.put("foo", new Integer(3));

自动装箱意味着第一个版本隐式转换为第二个版本。自动拆箱意味着您可以编写:

int i = myMap.get("foo");

而不是:

int i = myMap.get("foo").intValue();

对 的隐式调用意味着如果找不到键,它将生成一个 ,例如:intValue()NullPointerException

int i = myMap.get("bar"); // NullPointerException

原因是类型擦除。与 C# 不同,在 C# 中,泛型类型不会在运行时保留。它们只是用于显式铸造的“句法糖”,以节省您这样做的时间:

Integer i = (Integer)myMap.get("foo");

举个例子,这个代码是完全合法的:

Map<String, Integer> myMap = new HashMap<String, Integer>();
Map<Integer, String> map2 = (Map<Integer, String>)myMap;
map2.put(3, "foo");

答案 2

GNU Trove 支持这一点,但不使用泛型。http://trove4j.sourceforge.net/javadocs/gnu/trove/TObjectIntHashMap.html


推荐