为什么Map.containsKey()使用Object参数而不是专用类型? [英] Why Map.containsKey() takes an Object parameter instead of a speciallized type?
问题描述
可能重复:
>为什么使用Map.get的原因是什么(对象密钥)不是(完全)通用
Java泛型:为什么Map.get()会忽略类型?
Possible Duplicate:
What are the reasons why Map.get(Object key) is not (fully) generic
Java Generics: Why Does Map.get() Ignore Type?
Java Map interface is declared like this:
Interface Map<K,V>
它具有这样的方法:
boolean containsKey(Object key)
为什么不
boolean containsKey(K key)
?
On the contrary, the List interface has add method that takes parameter of generic type instead of Object
:
boolean add(E e).
推荐答案
这是您不能向List<? extends E>
添加任何内容的相同原因,因为编译器无法保证类型安全(并且类型擦除使运行时成为可能)检查不可能).
It's the same reason why you can't add anything to a List<? extends E>
because the compiler can't guarantee the type safety (and type erasure makes a runtime check impossible).
这意味着当您获得Map<? extends K,V>
时,将无法对其调用contains(K)
.但是contains
足够通用,以至于将随机Object
传递给它不会损坏接口(但会使一些错误更难识别).
This means that when you get a Map<? extends K,V>
you wouldn't be able to call contains(K)
on it. however contains
is general enough that passing random Object
s to it won't damage the interface (but makes some errors harder to pick up).
这篇关于为什么Map.containsKey()使用Object参数而不是专用类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!