30

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?

MalsR
  • 1,197
  • 1
  • 12
  • 23
Roman
  • 124,451
  • 167
  • 349
  • 456

2 Answers2

50

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);
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
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.

Nicholas
  • 15,916
  • 4
  • 42
  • 66