如果参数匹配多个方法签名,则定义调用什么方法?

What method is defined to be called if the argument matches multiple method signatures?

给出的代码:

public static void main(String[] args)
{
    doSomething(new ArrayList());
}

public static void doSomething(Collection collection) {
    System.out.println("Collection here!");
}

public static void doSomething(List list) {
    System.out.println("List here!");
}

这会按预期打印出 List here!,但是这种行为是否在 Java 规范中的某处定义,所以我可以依赖它,给定任何 Java 实现?

还有更有趣的行为:

public static void main(String[] args)
{
    Collection myCollection = new ArrayList();
    doSomething(myCollection);
}

public static void doSomething(Collection collection) {
    System.out.println("Collection here!");
}

public static void doSomething(List list) {
    System.out.println("List here!");
}

这将在此处打印 Collection!

在编译时选择调用的最具体的方法。

你的情况

ArrayList > List > Collection

因为 ArrayListList 的最具体的子类型,而列表是 Collection 的最具体的子类型。

这里是方法调用规则的规范

https://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.12.2.2