关于Java ArrayList继承containsAll方法的疑问:为何有两个继承来源?
Great question—this is actually a super common confusion when you start digging into the nitty-gritty of Java's collection hierarchy! Let's break this down step by step:
先理清ArrayList的继承/实现关系
First, remember that in Java, a class can extend one parent class and implement multiple interfaces. ForArrayList, the structure is:public class ArrayList<E> extends AbstractCollection<E> implements List<E>, RandomAccess, Cloneable, java.io.SerializableSo it's inheriting from the
AbstractCollectionclass and implementing theListinterface.为什么两个"来源"都有
containsAll?
TheListinterface defines the contract forcontainsAll—it specifies what the method is supposed to do (check if the list contains all elements of the given collection). Meanwhile,AbstractCollectionprovides a concrete implementation of this method that adheres to that contract.In Java 7 (which you're referencing), interfaces couldn't have default methods yet—so abstract classes like
AbstractCollectionexisted to provide reusable implementations of common collection methods, so every concrete collection class didn't have to rewrite the same code.这不会造成冲突吗?
Nope! When a class implements an interface and inherits from a class that already implements that interface's method, there's no conflict. The class just uses the implementation from its parent class (in this case,AbstractCollection'scontainsAll), which automatically satisfies the requirement from theListinterface.If
ArrayListwanted to change howcontainsAllworks, it could override the method—but it doesn't need to, since the parent class's implementation fits the interface's contract.为什么文档要同时标注两个来源?
The Oracle docs are just being thorough here. They list all the methods that are available to you when using anArrayListinstance, regardless of whether the method comes from a parent class or an implemented interface. It's a way to show you every "source" of the method in the hierarchy, even if they're referring to the same actual method implementation.
内容的提问来源于stack exchange,提问作者art74

