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

自古美人都是妖i 提交于 2019-12-20 17:37:44

问题


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 int by String and i+1 by i+"1", the compilation goes OK. What is wrong with in here?


回答1:


It's fine with Integer, but not okay with int - Java generics only work with reference types, basically :(

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



回答2:


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 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.



来源:https://stackoverflow.com/questions/2508918/why-does-the-java-compiler-not-like-primitive-int-as-type-for-values-in-hashmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!