Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 526
Roman Avatar asked Mar 24 '10 15:03

Roman


People also ask

Why is it not possible to use primitives in a HashMap?

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.

Can I use int in HashMap Java?

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

Can we use primitives as key in HashMap?

HashMap doesn't handle primitives, just objects.

Can integer be key in HashMap Java?

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.


2 Answers

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); } 
like image 134
Jon Skeet Avatar answered Sep 22 '22 11:09

Jon Skeet


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.

like image 24
Nicholas Avatar answered Sep 22 '22 11:09

Nicholas