int is a primitive type, you can read what does mean a primitive type in java here, and a Map is an interface that has to objects as input:
public interface Map<K extends Object, V extends Object>
object means a class, and it means also that you can create an other class that exends from it, but you can not create a class that exends from int. So you can not use int variable as an object. I have tow solutions for your problem:
Map<String, Integer> map = new HashMap<>();
or
Map<String, int[]> map = new HashMap<>();
int x = 1;
//put x in map
int[] x_ = new int[]{x};
map.put("x", x_);
//get the value of x
int y = map.get("x")[0];
You can use reference type in generic arguments, not primitive type. So here you should use
Map<String, Integer> myMap = new HashMap<String, Integer>();
and store value as
myMap.put("abc", 5);
You cannot use primitive types in HashMap
. int
, or double
don't work. You have to use its enclosing type. for an example
Map<String,Integer> m = new HashMap<String,Integer>();
Now both are objects, so this will work.
GNU Trove support this but not using generics. http://trove4j.sourceforge.net/javadocs/gnu/trove/TObjectIntHashMap.html
Source: Stackoverflow.com