java:HashMap< String,int>不工作 [英] java: HashMap<String, int> not working

查看:525
本文介绍了java:HashMap< String,int>不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

HashMap<String, int> doesn't seem to work but HashMap<String, Integer> does work. Any ideas why?

推荐答案

Java中不能使用基本类型作为泛型参数。改为使用:

You can't use primitive types as generic arguments in Java. Use instead:

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

使用 auto-boxing / unboxing 代码没有什么区别。自动装箱意味着你可以写:

With auto-boxing/unboxing there is little difference in the code. Auto-boxing means you can write:

myMap.put("foo", 3);

而不是:

instead of:

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

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

Auto-boxing means the first version is implicitly converted to the second. Auto-unboxing means you can write:

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

而不是:

instead of:

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

intValue()的隐式调用表示如果未找到密钥,它将生成 NullPointerException ,例如:

The implicit call to intValue() means if the key isn't found it will generate a NullPointerException, for example:

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

原因是 type erasure 。与C#不同,通用类型不会在运行时保留。它们只是语法糖,用于显式投射以节省您的工作:

The reason is type erasure. Unlike, say, in C# generic types aren't retained at runtime. They are just "syntactic sugar" for explicit casting to save you doing this:

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

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

To give you an example, this code is perfectly legal:

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

这篇关于java:HashMap&lt; String,int&gt;不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆