列表< E> .contains(Object),为什么? [英] List<E>.contains(Object), why?
问题描述
可能存在重复:
为什么Map.get(Object key)不是(完全)通用的原因
为什么我们要包含(Object o)而不是Containers(E e)?
大家可以看到这里,一个模板化的java类型E的.util.List的包含
方法,但不是模板化的:它取而代之需要一个 Object
。有人知道为什么吗?
在什么情况下会是 List< String>
在 myList.contains(new OtherNonString( ))
?如果我没有弄错,除非它与之相比的对象具有类型E作为祖先(在我的字符串示例中,由于 String
不可能是最终的)
仅仅是为了保持与预先仿制版本的向后兼容性?我错过了一个有用的用例吗?如果只是为了向后兼容,为什么不弃用 contains(Object)
并创建 contains(E)
?
编辑:
我的一些子问题已经回答过了。作为参考,也请查看这个问题
如果只是为了向后兼容,为什么不弃用
contains(Object)和创建一个contains(E)?
因为包含(Object)
和包含(E)
具有相同类型的擦除(您可以在此代码中看到示例),因此会导致编译错误。此外,弃用方法不是一种选择,当时的首要任务是让遗留代码工作。
Possible Duplicate:
What are the reasons why Map.get(Object key) is not (fully) generic
Why do we have contains(Object o) instead of contains(E e)?
As you all can see here, a templated java.util.List of type E has its contains
method not templated: it takes an Object
instead. Does anyone know why?
in what case would a List<String>
return true in myList.contains(new OtherNonString())
? If I'm not mistaken, never, unless the object that it's compared to has type E as an ancestor (which in my string example is impossible due to String
being final)
Is it only to maintain backwards compatibility with pre-generics versions? am I missing a use-case where it makes sense? if it's just for backwards compatibility, why not deprecate contains(Object)
and create a contains(E)
?
Edit:
Some of my sub-questions had been answered before. For reference, also check this question
if it's just for backwards compatibility, why not deprecate contains(Object) and create a contains(E)?
Because contains(Object)
and contains(E)
have the same type erasure (as you can see in this code sample) and hence would cause compilation errors. Also, deprecating methods was not an option, the top priority back then was to make legacy code work.
这篇关于列表< E> .contains(Object),为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!