这是Map
的接口合同 - 因此您必须按照原样执行合同。
不过,我认为有两个原因,为什么Map
这部分的设计是一件好事:
i)本Map
contract是,你可以在下列情况下得到的映射值:
如果此映射包含从密钥k到值v的映射,使得 (key == null?k == null:key.equals(k)),则此方法返回v; 否则返回null。如果此映射包含指定键的映射关系
返回true:(可以有至多一个这样的映射。)
或等价,而具体到你的问题有关containsKey(Object key)
。更正式地说,当且仅当此映射包含关键字k的映射(key == null?k == null:key.equals(k))时才返回true。 (可以有至多一个这样的映射。)
这样,你不关心打字,而是平等。
II)这是真的只是同一个点,但考虑到以下几点:
Map<String, Integer> map = new HashMap<>();
String key = "A Key";
Integer value = 1;
map.put(key, value);
Object objectKey = key; // this is the same key object, but it is typed as Object
map.containsKey(objectKey); // what would you want/expect this to return?
map.get(objectKey); // ...or this?
因此,对于您的实现的Map
,我不会建议只是铸造Object
键(你会得到一个运行时异常...)。你决定如何实现它取决于你的设计。让我们设想一下,你在保存类型列表中的键和值...然后你会被告知铸造前检查instanceof
的Object
键:
public boolean containsKey(Object key) {
if (key instanceof K) {
// do your thing...
} else {
return false;
}
}
注意instanceof
检查基础对象的类型,而不是其声明的类型,所以:
String key = "A Key";
Object objectKey = key;
boolean isString = (objectKey instanceof String); // is true
真的,我会建议,而不是询问如何给力的东西,违背了合同Map
,你要会问这个问题"why is the contract that way?” ......
你的第二个陈述是什么意思? –
这个问题有一些有趣的答案,为什么'Map'接口不使用通用类型的某些方法参数:http://stackoverflow.com/questions/857420/what-are-the-reasons-why-map-getobject关键不是完全通用的 – andersschuller
@RohitJain我编辑了这个问题。希望它更好地知道。但是代码举例说明,由于接口契约,我必须处理一个对象,但我希望V确信我有可能依赖于ValueInterface属性。 – fabiim