您不能在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");



