[英]Why does the Java compiler not like primitive int as type for values in HashMap?
The compiler complains about this code: 编译器抱怨这段代码:
HashMap<String,int> userName2ind = new HashMap<String,int>();
for (int i=0; i<=players.length; i++) {
userName2ind.put(orderedUserNames[i],i+1);
}
It writes "unexpected type" and point on int
. 它写出“意外类型”并指向
int
。 If I replace int
by String
and i+1
by i+"1"
, the compilation goes OK. 如果我用
String
替换int
而i+1
用i+"1"
替换,则编译就可以了。 What is wrong with in here? 这里有什么问题?
It's fine with Integer
, but not okay with int
- Java generics only work with reference types , basically :( 它对
Integer
很好,但对int
不行 - Java泛型只能使用引用类型 ,基本上:(
Try this - although be aware it will box everything: 试试这个 - 虽然要知道它会包装一切:
HashMap<String,Integer> userName2ind = new HashMap<String,Integer>();
for (int i=0; i<=players.length; i++) {
userName2ind.put(orderedUserNames[i],i+1);
}
If you have small collections, then using reference types is probably fine, but there are alternatives and good one is trove4j . 如果你有小集合,那么使用引用类型可能没什么问题,但有其他选择,而且好的是trove4j 。 Trove does a pretty good job of recreating the collections API using pure primitives.
Trove在使用纯原语重新创建集合API方面做得非常好。 The payoff is much lower memory usage and in many cases, better performance when inserting/looking up.
收益大大降低了内存使用率,在许多情况下,插入/查找时性能更高。 Your example would look like this:
您的示例如下所示:
TObjectIntHashMap<String> userName2ind = new TObjectIntHashMap<String>();
for (int i=0; i<=players.length; i++) {
userName2ind.put(orderedUserNames[i],i+1);
}
The only downside, in my experience, is the absence of concurrent implementations of these, so you have to figure out another way to manage thread safety. 根据我的经验,唯一的缺点是没有这些的并发实现,所以你必须找到另一种管理线程安全的方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.