问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/4677804/why-is-java-util-map-get-not-generic