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.
myHashMap.put(1L, "value"); 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.
myHashMap.get(1L); 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 get method?
The argument that I pass should have the same datatype as the datatype of the Key which I use while instantiating my hashmap.
getTyped.... In Java you can do this with static method, so your call will begetTyped(map, key). Ugly, but works.getmethod, something like this:Integer getMapValue(Map map, String Key){ return map.get(key) }And call this method instead of the get method, but I wanted to know if Java provides any such restricting feature of not?get(K key)method, but It seems like an unnecessary effort. The return value for a mismatching key (type-wise) will be null, as expected. So the Map will conform to its API.