开发者

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

开发者 https://www.devze.com 2022-12-23 20:13 出处:网络
The compiler complains about this code: HashMap<String,int> userName2ind = new HashMap<String,int>();

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?


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号