Why does the Java compiler not like primitive int as type for values in HashMap?
Solution 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);
}
Solution 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.
Roman
Updated on April 25, 2020Comments
-
Roman about 4 years
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 replaceint
byString
andi+1
byi+"1"
, the compilation goes OK. What is wrong with in here?