Reputation: 1488
HashMap<String, int>
doesn't seem to work but HashMap<String, Integer>
does work.
Any ideas why?
Upvotes: 148
Views: 313725
Reputation: 309
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 two objects as input:
public interface Map<K extends Object, V extends Object>
Object
means a class, and it also means that you can create another class that extends from it, but you can not create a class that extends from int.
So you can not use int variable as an object. I have two 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];
Upvotes: 2
Reputation:
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.
Upvotes: 2
Reputation: 149
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);
Upvotes: -3
Reputation: 533492
GNU Trove support this but not using generics. http://trove4j.sourceforge.net/javadocs/gnu/trove/TObjectIntHashMap.html
Upvotes: 5
Reputation: 625057
You can't use primitive types as generic arguments in Java. Use instead:
Map<String, Integer> myMap = new HashMap<String, Integer>();
With auto-boxing/unboxing there is little difference in the code. Auto-boxing means you can write:
myMap.put("foo", 3);
instead of:
myMap.put("foo", new Integer(3));
Auto-boxing means the first version is implicitly converted to the second. Auto-unboxing means you can write:
int i = myMap.get("foo");
instead of:
int i = myMap.get("foo").intValue();
The implicit call to intValue()
means if the key isn't found it will generate a NullPointerException
, for example:
int i = myMap.get("bar"); // NullPointerException
The reason is type erasure. Unlike, say, in C# generic types aren't retained at runtime. They are just "syntactic sugar" for explicit casting to save you doing this:
Integer i = (Integer)myMap.get("foo");
To give you an example, this code is perfectly legal:
Map<String, Integer> myMap = new HashMap<String, Integer>();
Map<Integer, String> map2 = (Map<Integer, String>)myMap;
map2.put(3, "foo");
Upvotes: 228