为什么Java的TreeSet< E> remove(Object)不带E
问题描述:
从Java 6 TreeSet< E> 文档:
From the Java 6 TreeSet<E>
Documentation:
boolean remove(Object o):
Removes the specified element from this set if it is present.
为什么接受Object而不是通用类型E?唯一可以添加的对象是E类型,因此,只有可移除类型应该是E类型。
Why does this accept an Object instead of the generic type E? The only objects that can be added are of type E, so it follows that the only removable type should be of type E.
答
等于,则需要 c> remove()
元素(按 .equals()
)。在Java中,不同类的对象是可能的(在某些情况下也是必需的)是相等的。因此,您不应限制类型。
remove()
, like get()
is required to work when given an equal element (in terms of .equals()
). In Java, it is possible (and in some cases, required) for objects of different classes to be equal. Hence, you shouldn't restrict the type.