Why are methods declared in the collection also duplicated in the list interface?

Is there any specific reason (other than the one below) why all methods declared in java.util.Collection are duplicated in the java.util.List interface?

According to java.util.List Api:

The List interface sets additional conditions, in addition to those specified in the Collection interface, in iterator contracts, add, remove, equals and hashCode. Declarations for other legacy methods are also included here for convenience.

Just for additional documentation (conditions) is it useful to repeat the method declarations?

+6
source share
2 answers

Just for additional documentation (conditions) is it useful to repeat the method declarations?

How would you do otherwise? What is the disadvantage?

Yes, this is the easiest way to do this.

+2
source

The List interface contains additional conditions, other than those specified in the Collection interface, on iterator contracts, add, delete, equals and hashCode. Declarations for other inherited methods are also included here for convenience.

For example, the Javadoc add method inside the List interface reads:

Adds the specified item to the end of this list (optional operation).

Lists that support this operation may limit the ability of items to be added to this list. In particular, some lists refuse to add null elements, while others will impose restrictions on the type of elements that can be added. The list of classes should clearly indicate in its documentation any restrictions on what elements can be added.

, while the Javadoc add method inside the Collection interface reads:

Ensures that this collection contains the specified item (optional operation). Returns true if this collection has changed as a result of a call. (Returns false if this collection does not allow duplication and already contains the specified element.)

Collections that support this operation may limit the ability of items to be added to this collection. In particular, some collections will refuse to add null elements, while others will impose restrictions on the type of elements that can be added. Collection classes should clearly indicate in their documentation any restrictions on which items can be added.

If the collection refuses to add any item for any reason other than the fact that it already contains the item, it should throw an exception (instead of returning false). This preserves the invariant that the collection always contains the specified item after which call returns.

0
source

All Articles