HashMap<String, int>似乎不起作用,但HashMap<String, Integer>确实有效.有什么想法吗?
cle*_*tus 192
您不能在Java中将原始类型用作通用参数.改为使用:
Map<String, Integer> myMap = new HashMap<String, Integer>();
Run Code Online (Sandbox Code Playgroud)
使用自动装箱/拆箱时,代码几乎没有差别.自动装箱意味着你可以写:
myMap.put("foo", 3);
Run Code Online (Sandbox Code Playgroud)
代替:
myMap.put("foo", new Integer(3));
Run Code Online (Sandbox Code Playgroud)
自动装箱意味着第一个版本被隐式转换为第二个版本.自动拆箱意味着您可以写:
int i = myMap.get("foo");
Run Code Online (Sandbox Code Playgroud)
代替:
int i = myMap.get("foo").intValue();
Run Code Online (Sandbox Code Playgroud)
隐式调用intValue()意味着如果找不到密钥,它将生成一个NullPointerException,例如:
int i = myMap.get("bar"); // NullPointerException
Run Code Online (Sandbox Code Playgroud)
原因是类型擦除.与C#不同,泛型类型不会在运行时保留.它们只是用于显式转换的"语法糖"来保存你这样做:
Integer i = (Integer)myMap.get("foo");
Run Code Online (Sandbox Code Playgroud)
举个例子,这段代码非常合法:
Map<String, Integer> myMap = new HashMap<String, Integer>();
Map<Integer, String> map2 = (Map<Integer, String>)myMap;
map2.put(3, "foo");
Run Code Online (Sandbox Code Playgroud)