问题
HashMap<String, int>
似乎不起作用但是HashMap<String, Integer>
可以工作。有什么想法吗?
#1 热门回答(180 赞)
你不能在Java中将原始类型用作通用参数。改为使用:
Map<String, Integer> myMap = new HashMap<String, Integer>();
与auto-boxing/unboxing在代码上差别不大。自动装箱意味着你可以写:
myMap.put("foo", 3);
代替:
myMap.put("foo", new Integer(3));
自动装箱意味着第一个版本被隐式转换为第二个版本。自动拆箱意味着你可以写:
int i = myMap.get("foo");
代替:
int i = myMap.get("foo").intValue();
隐含调用intValue()
意味着如果找不到密钥,它将生成aNullPointerException
,例如:
int i = myMap.get("bar"); // NullPointerException
原因是type erasure。与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 热门回答(3 赞)
GNU Trove支持此但不使用泛型.http://trove4j.sourceforge.net/javadocs/gnu/trove/TObjectIntHashMap.html
#3 热门回答(2 赞)
你不能在HashMap
.int
或double
中使用原始类型。你必须使用它的封闭类型。举个例子
Map<String,Integer> m = new HashMap<String,Integer>();
现在两者都是对象,所以这将起作用。