简体   繁体   中英

Java: Why does Set<E> mention all methods in Collection<E>

http://download.oracle.com/javase/tutorial/collections/interfaces/set.html

Why does Set interface list all the methods in Collection? Aren't these methods automatically inherited by the child interface?

它列出了所有这些,因为文档是不同的,即使声明本身是相同的。

That link is a tutorial , not the API docs. Try this link:

http://download.oracle.com/javase/6/docs/api/java/util/Set.html

Set works different then Collection - in Set you can have no duplicate entries. If you would just copy methods from Collection you would implement Set wrong...

Like Kathy wrote - documentation is different (because logic/use is different)

Collection .add():

Ensures that this collection contains the specified element (optional operation). Returns true if this collection changed as a result of the call. (Returns false if this collection does not permit duplicates and already contains the specified element.) Collections that support this operation may place limitations on what elements may be added to this collection. In particular, some collections will refuse to add null elements, and others will impose restrictions on the type of elements that may be added. Collection classes should clearly specify in their documentation any restrictions on what elements may be added.

If a collection refuses to add a particular element for any reason other than that it already contains the element, it must throw an exception (rather than returning false). This preserves the invariant that a collection always contains the specified element after this call returns.

Set .add():

Adds the specified element to this set if it is not already present (optional operation). More formally, adds the specified element e to this set if the set contains no element e2 such that (e==null ? e2==null : e.equals(e2)). If this set already contains the element, the call leaves the set unchanged and returns false. In combination with the restriction on constructors, this ensures that sets never contain duplicate elements. The stipulation above does not imply that sets must accept all elements; sets may refuse to add any particular element, including null, and throw an exception, as described in the specification for Collection.add. Individual set implementations should clearly document any restrictions on the elements that they may contain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM