为什么 Java 编译器不喜欢原始 int 作为 HashMap 中值的类型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2508918/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:37:12  来源:igfitidea点击:

Why does the Java compiler not like primitive int as type for values in HashMap?

javatypesintegerhashmap

提问by Roman

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. If I replace intby Stringand i+1by i+"1", the compilation goes OK. What is wrong with in here?

它写入“意外类型”并指向int. 如果我用intbyStringi+1by替换i+"1",编译就可以了。这里有什么问题?

采纳答案by Jon Skeet

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);
}

回答by Nicholas

If you have small collections, then using reference types is probably fine, but there are alternatives and good one is trove4j. Trove does a pretty good job of recreating the collections API using pure primitives. The payoff is muchlower memory usage and in many cases, better performance when inserting/looking up. Your example would look like this:

如果您的集合很小,那么使用引用类型可能没问题,但也有其他选择,最好的方法是trove4j。Trove 在使用纯原语重新创建集合 API 方面做得非常好。回报是多少更低的内存使用率,并在许多情况下,将更好的性能时/仰视。您的示例如下所示:

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.

根据我的经验,唯一的缺点是缺乏这些的并发实现,因此您必须找出另一种管理线程安全的方法。