为什么HashSet< E>不限制包含()和删除()中E的参数类型 [英] Why does HashSet<E> not restrict type of argument to E in contains() and remove()
问题描述
可能重复:
Map.get(Object key)不是(完全)通用的原因是什么?
为什么Java的TreeSet< E>删除(对象)不带E
为什么HashSet不限制类型E的参数在这里:
Why does HashSet not restrict type of argument to E here:
public boolean contains(Object o)
public boolean remove(Object o)
就像添加()
public boolean add(E e)
我的意思是如果编译器正在执行只添加了E类型的对象,那么该集合不能包含/删除任何其他类型
I mean if the compiler is enforcing that only objects of type E are being added, then the set can't contain/remove any other type
推荐答案
区别在于添加必须是类型安全的,以保持集合的完整性,而项目检查/删除可以提供类型宽容,而不会有损害集合类型安全的风险。换句话说,如果添加错误类型的元素,该集将变为无效;另一方面,如果您检查是否存在错误类型的元素,您只需返回 false
。同样适用于 remove
:如果传递不兼容类型的元素,它将不会出现在 + 集合中,因此删除将会进行成为一个无操作者。
+ 除非你通过一个利用类型擦除的黑客入侵它。
The difference is that adding must be type-safe to preserve the integrity of the collection, while item checking/removal can afford to be "type-forgiving" without the risk of harming type safety of the collection. In other words, if you add an element of a wrong type, the set will become invalid; on the other hand, if you check for a presence of an element of a wrong type, you'll simply get back a false
. Same goes for remove
: if you pass an element of an incompatible type, it's not going to be in the set +, so the removal is going to be a no-op.
+ Unless you put it in through a hack that exploits type erasure.
这篇关于为什么HashSet< E>不限制包含()和删除()中E的参数类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!