JDK源码:代码重复Collection.java和Set.java

gef*_*fei 4 java

在 JDK 8 中,java.util.Collection

public interface Collection<E> extends Iterable<E> {
    // Query Operations

    /**
     * Returns the number of elements in this collection.  If this collection
     * contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
     * <tt>Integer.MAX_VALUE</tt>.
     *
     * @return the number of elements in this collection
     */
    int size();
Run Code Online (Sandbox Code Playgroud)

有趣的是,java.util.Set

public interface Set<E> extends Collection<E> {
    // Query Operations

    /**
     * Returns the number of elements in this set (its cardinality).  If this
     * set contains more than <tt>Integer.MAX_VALUE</tt> elements, returns
     * <tt>Integer.MAX_VALUE</tt>.
     *
     * @return the number of elements in this set (its cardinality)
     */
    int size();
Run Code Online (Sandbox Code Playgroud)

覆盖接口中的方法声明的目的是什么?为什么extends不够?

EDIT java.util.List还显示了冗余,并且 的 javadoc 与List.size()的仅略有不同Collection.size(),并且没有引入任何新术语:

public interface List<E> extends Collection<E> {
// Query Operations

/**
 * Returns the number of elements in this list.  If this list contains
 * more than <tt>Integer.MAX_VALUE</tt> elements, returns
 * <tt>Integer.MAX_VALUE</tt>.
 *
 * @return the number of elements in this list
 */
int size();
Run Code Online (Sandbox Code Playgroud)

Bri*_*etz 6

除了改变行为之外,覆盖方法还有很多用途。它可以更改方法的签名(使用协变覆盖来改进返回类型)、添加注释、扩大可访问性(将受保护的方法在子类中变为公共方法)或改进规范(表示为 Javadoc)。在这种情况下,覆盖存在以便SetJavadoc 可以定义术语“基数”。

  • 覆盖方法似乎有点肤浅的原因。 (3认同)