为什么java.util.Map.get(...)不是通用的? [英] Why is java.util.Map.get(...) not generic?
问题描述
可能重复:
Map.get(Object key)不是(完全)通用的原因是什么?
此方法和Map界面中的其他一些方法不是通用的。几乎任何地方都有一个关键值作为参数,它接受Object,即remove,get和containsKey。
任何想法,为什么他们做出这个决定。我的假设是支持遗留代码,但对我来说,我认为这是一个弱势。
任何人都可以为我提供一个特定的原因最好接受Object而不是KeyType。
用于检索/删除/检查给定键的存在的对象需要不一定与用于存储它的对象的类型相同(=键)。
需要等于
并返回相同的 hashCode
作为关键,但规范中没有任何内容必须是相同的类型。
这个事实很少被使用,大多数时候你将使用与用于存储它们的密钥相同的密钥(或至少是相同类型的对象)来检索值。
但是,由于这是旧 HashMap
中的支持用例,所以需要在泛型版本中支持。 / p>
请注意,所有方法 keySe t()
使用特定类型,因为当调用 put()
时,它肯定会返回用作键的对象。
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.
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.
这篇关于为什么java.util.Map.get(...)不是通用的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!