HashMap<String, int>
似乎不起作用,但HashMap<String, Integer>
确实起作用。有什么想法吗?
您不能在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#不同,泛型类型不会在运行时保留。它们只是显式转换的“语法糖”,可以节省您这样做的时间:
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");
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句