Reputation: 25
So as you can see be title I am confused on:
Map<String, int> list = new HashMap<String, int>
I am a bit lost in class on this specific topic and would appreciate if anybody could explain why and how it actually works.
Upvotes: 1
Views: 3621
Reputation: 1648
IN java Some thing like following happens
public interface Map<K, V> {
public K getKey();
public V getValue();
}
public class HashMap<K, V> implements Map<K, V> {
private K key; //1
private V value; //2
public K getKey() { return key; }
public V getValue() { return value; }
//other getter setter methods
}
As In Here in place of<K,V> in
<String,int> int
is a primitive type And we can't make object of primitive type
.
see //1 and //2 above in code
But <String,Integer> is possible as they are wrapper type and Objects can be made of them
Upvotes: 1
Reputation: 178333
The type int
is not a class, it's a primitive type. Generic type parameters must be assigned classes, not primitive types. You can use
Map<String, Integer> list = new HashMap<String, Integer>();
instead. All Java primitive types have class wrappers, and as of Java 1.5, autoboxing allows expressions such as map.put("dummy", 1);
, where 1
is autoboxed as an Integer
.
Incidentally, it can be confusing to call a Map
list
. You could remove the confusion by calling it map
.
Upvotes: 11