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?
We can't use primitive types because of a restriction around the way generics were designed. A HashMap allows one null key and multiple null values. It doesn't preserve the order of the elements and doesn't guarantee the order will remain the same over time.
In the ArrayList chapter, you learned that Arrays store items as an ordered collection, and you have to access them with an index number ( int type). A HashMap however, store items in "key/value" pairs, and you can access them by an index of another type (e.g. a String ).
HashMap doesn't handle primitives, just objects.
It can store different types: Integer keys and String values or same types: Integer keys and Integer values. HashMap is similar to HashTable, but it is unsynchronized. It is allowed to store null keys as well, but there can only be one null key and there can be any number of null values.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With