You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

关于Java ArrayList继承containsAll方法的疑问:为何有两个继承来源?

解答:ArrayList为何能从两个来源继承同一个方法?

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. For ArrayList, the structure is:

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

    So it's inheriting from the AbstractCollection class and implementing the List interface.

  • 为什么两个"来源"都有containsAll?
    The List interface defines the contract for containsAll—it specifies what the method is supposed to do (check if the list contains all elements of the given collection). Meanwhile, AbstractCollection provides 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 AbstractCollection existed 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's containsAll), which automatically satisfies the requirement from the List interface.

    If ArrayList wanted to change how containsAll works, 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 an ArrayList instance, 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:41:29