Java 中的 ArrayList 没有实现 Collection 接口的方法?
ArrayList in Java doesn't implement methods from Collection interface?
我目前对这个问题有点困惑。我注意到 ArrayList 是一个实现 List 的 class,List 又扩展了 Collection。
在Collection<?>
中我们有一堆方法,其中一个是containsAll()
。我查看了ArrayList
的官方文档,但是可以看到Array list没有这样的方法。在页面的页脚中写了一些东西,说 "inherited methods" 并且那里提到了 containsAll()
。
我(从文档中)不明白的是,containsAll()
是否已定义,即使它在 ArrayList class 中有一个空主体,还是根本没有?如果不是,这是否违反了 Java 的规则?
还有其他人"missing"以同样的方式?!
containsAll()
方法由 AbstractCollection
定义,由 AbstractList
扩展,后者又由 ArrayList
扩展。所以 ArrayList
继承 containsAll()
实现。
考虑以下代码:
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
boolean contains = list.containsAll(Arrays.asList("b", "c"));
这里调用list.containsAll()
时,实际上执行的是AbstractCollection
中声明的方法
ArrayList 扩展了 AbstractList,后者扩展了 AbstractCollection.
在那里你可以找到它:
Returns true if this collection contains all of the elements in the specified collection.
This implementation iterates over the specified collection, checking each element returned by the iterator in turn to see if it's contained in this collection. If all elements are so contained true is returned, otherwise false.
基本上这里真正的答案是:注意ArrayList的javadoc的top,在那里你可以找到继承树:
java.lang.Object
java.util.AbstractCollection<E>
java.util.AbstractList<E>
java.util.ArrayList<E>
我目前对这个问题有点困惑。我注意到 ArrayList 是一个实现 List 的 class,List 又扩展了 Collection。
在Collection<?>
中我们有一堆方法,其中一个是containsAll()
。我查看了ArrayList
的官方文档,但是可以看到Array list没有这样的方法。在页面的页脚中写了一些东西,说 "inherited methods" 并且那里提到了 containsAll()
。
我(从文档中)不明白的是,containsAll()
是否已定义,即使它在 ArrayList class 中有一个空主体,还是根本没有?如果不是,这是否违反了 Java 的规则?
还有其他人"missing"以同样的方式?!
containsAll()
方法由 AbstractCollection
定义,由 AbstractList
扩展,后者又由 ArrayList
扩展。所以 ArrayList
继承 containsAll()
实现。
考虑以下代码:
List<String> list = new ArrayList<>();
list.add("a");
list.add("b");
boolean contains = list.containsAll(Arrays.asList("b", "c"));
这里调用list.containsAll()
时,实际上执行的是AbstractCollection
中声明的方法
ArrayList 扩展了 AbstractList,后者扩展了 AbstractCollection.
在那里你可以找到它:
Returns true if this collection contains all of the elements in the specified collection.
This implementation iterates over the specified collection, checking each element returned by the iterator in turn to see if it's contained in this collection. If all elements are so contained true is returned, otherwise false.
基本上这里真正的答案是:注意ArrayList的javadoc的top,在那里你可以找到继承树:
java.lang.Object
java.util.AbstractCollection<E>
java.util.AbstractList<E>
java.util.ArrayList<E>