Possible Duplicate:
What are the reasons why Map.get(Object key) is not (fully) generic
This method and a number of other methods in the Map interface are not generic. Almost anywhere a key value is expected as a parameter, it accepts Object instead, namely remove, get and containsKey.
Any idea as to why they made this decision. My assumption is that it was done to support legacy code, but to me, I think that is a weak position.
Can anyone provide me a specific reason why it would be preferable to accept Object here instead of KeyType.
HashMap stores key, value pairs and it does not allow duplicate keys. If the key is duplicate then the old key is replaced with the new value.
However, none of the existing Java core Map implementations allow a Map to handle multiple values for a single key. As we can see, if we try to insert two values for the same key, the second value will be stored, while the first one will be dropped.
The term generic simply is the idea of allowing the type (Integer, Double, String, etc. or any user-defined type) to be the parameter to methods, class, or interface. For eg, all the inbuilt collections in java like ArrayList, HashSet, HashMap, etc. use generics.
The objects used to retrieve/remove/check for existance of a given key need not necessarily be of the same type as the object used to store it (= the key).
It needs to be equal
and return the same hashCode
as the key, but nothing in the spec says that it must be of the same type.
That fact is rarely used and most of the time you'll retrieve the values with the same keys (or at least objects of the same types) as the ones you use to store them.
But since that was a supported use case in the "old" HashMap
, it needs to be supported in the generics version as well.
Note that all methods that keySet()
uses the specific type, as it's sure to return exactly the objects used as keys when put()
was called.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With