ArrayList.java中List接口的冗余实现
可能重复:
为什么ArrayList有“实现List”?
我是java新手我试图看到集合界面的层次结构。 我发现AbstractList.java的签名就像
public abstract class AbstractList extends AbstractCollection implements List
它实现了List接口。 但是,如果你看看子类ArrayList.java的签名,它看起来像
public class ArrayList extends AbstractList implements List, RandomAccess, Cloneable, java.io.Serializable
如果你看父类已经实现了List接口那么为什么子类再次实现相同的接口( List )。
这背后是否有具体的原因或要求
这背后是否有具体的原因或要求
我不这么认为。 就编译器而言,删除第二个List
将完全没有改变。
我的两个假设是:
- 这是出于历史原因。 但是,我找不到任何证据支持这一点。
- 它包含在文档中,以使其立即清除,而不是
ArrayList
是一个List
(这可能是关于ArrayList
最重要的事情)。
我不知道答案是什么,所以我做了一些研究。 事实certificate,这是为了清晰。
是。 它可能已被省略。 但是因此可以立即看到它是一个List。 否则,需要额外点击代码/文档。 我认为这就是原因 – 清晰度。
并添加Joeri Hendrickx评论的内容 – 它是为了显示ArrayList实现List。 整个画面中的AbstractList只是为了方便起见,减少了List实现之间的代码重复。
为什么ArrayList有“实现List”?
可能只是出于文档目的,为想要使用ArrayList的人清楚地说明。
它确实是多余的,因为ArrayList的AbstractList超类已经实现了List接口。
来自Java Ranch
另一个原因可能是:
// This class captures common code shared by both the ArrayList and LinkedList. // An abstract class is a good way to provide a partially implemented class, or // a partial implementation of an interface. Notice that the header of this // class claims to implement the List interface, but the file doesn't write // all of the methods. // // Java allows this file to compile because it knows that the abstract class // must be extended to complete it. If a subclass of AbstractList doesn't // implement all the rest of the List interface's methods, that subclass will // not compile.
我在这里找到了 。