This question already has an answer here:
I have instantiated my HashMap like this:
Map<String, Integer> myHashMap = new HashMap<String, Integer>();
The datatype of the
Key is String, so when I try to insert a new key-value pair in the map keeping the
Key as Integer, it throws an error.
That means in the put method they have restricted the datatype of the
Key. But while fetching the value from the map using the
get method it is not checking for the datatype of the
Key. So if I write something like this, it doesn't give a compilation error.
I checked the
get method in the Java Map interface and its parameter type is
Object, so that's why it is allowing any Object as the put method argument.
V get(Object key)
Is there a way I can restrict the datatype which I pass as an argument in the
The argument that I pass should have the same datatype as the datatype of the
Key which I use while instantiating my hashmap.