15

可能重复:
为什么 ArrayList 有“implements List”?

我是 java 新手,我试图查看集合接口的层次结构。我发现 AbstractList.java的签名就像

public abstract class AbstractList<E> extends AbstractCollection<E> implements List<E>

它实现了 List 接口。但是,如果您查看子类 ArrayList.java 的签名,它看起来像

public class ArrayList<E> extends AbstractList<E>   implements List<E>, RandomAccess, Cloneable, java.io.Serializable

如果您查看父类已经实现 List 接口,那么为什么子类再次实现相同的接口(List)。

这背后是否有特定的原因或要求

4

3 回答 3

8

这背后是否有特定的原因或要求

我不这么认为。就编译器而言,删除第二个List<E>绝对不会改变。

我的两个假设是:

  1. 它的存在是出于历史原因。但是,我找不到任何证据来支持这一点。
  2. ArrayList<E> 它包含在文档中,比is-a 更清楚List<E>(这可能是最重要的事情ArrayList)。
于 2012-12-20T14:11:04.763 回答
3

我不知道答案是什么,所以我做了一些研究。事实证明,这是为了清楚起见。

是的。它可以被省略。但因此可以立即看出它是一个列表。否则需要额外点击代码/文档。我认为这就是原因——清晰。

并添加 Joeri Hendrickx 的评论 - 目的是展示 ArrayList 实现了 List。整个图中的 AbstractList 只是为了方便和减少 List 实现之间的代码重复。

为什么 ArrayList 有“实现列表”?

于 2012-12-20T14:11:17.173 回答
0

可能只是出于文档目的,让想要使用 ArrayList 的人清楚。

这确实是多余的,因为 ArrayList 的 AbstractList 超类已经实现了 List 接口。

来自爪哇牧场

另一个原因可能是:

// 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. 

我在这里找到了。

于 2012-12-20T14:10:50.347 回答