gpt4 book ai didi

java - Java 使用普通签名而不是可变参数是标准行为吗?

转载 作者:行者123 更新时间:2023-12-02 01:23:16 24 4
gpt4 key购买 nike

我有下一个类:

public class Matrix implements ITensor {

public double get(int row, int column) {
return mData[row][column];
}

@Override
public double get(int... indices) {
return get(indices[0], indices[1]);
}
}

所以get(r, c)适合两种签名,Java 会调用第一个声明(当然,我可以检查,我的意思是这是否是标准行为)?在这种情况下,JVM 如何选择方法签名?

P.S.似乎这是一个新手的问​​题,但我自己找不到信息

最佳答案

TL;DR 永远不会选择可变参数方法而不是非可变参数方法。

参见 JLS 15.12.2. Compile-Time Step 2: Determine Method Signature :

The process of determining applicability begins by determining the potentially applicable methods (§15.12.2.1). Then, to ensure compatibility with the Java programming language prior to Java SE 5.0, the process continues in three phases:

  1. The first phase performs overload resolution without permitting boxing or unboxing conversion, or the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the second phase.

    This guarantees that any calls that were valid in the Java programming language before Java SE 5.0 are not considered ambiguous as the result of the introduction of variable arity methods, implicit boxing and/or unboxing. However, the declaration of a variable arity method (§8.4.1) can change the method chosen for a given method method invocation expression, because a variable arity method is treated as a fixed arity method in the first phase. For example, declaring m(Object...) in a class which already declares m(Object) causes m(Object) to no longer be chosen for some invocation expressions (such as m(null)), as m(Object[]) is more specific.

  2. The second phase performs overload resolution while allowing boxing and unboxing, but still precludes the use of variable arity method invocation. If no applicable method is found during this phase then processing continues to the third phase.

    This ensures that a method is never chosen through variable arity method invocation if it is applicable through fixed arity method invocation.

  3. The third phase allows overloading to be combined with variable arity methods, boxing, and unboxing.

关于java - Java 使用普通签名而不是可变参数是标准行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57318786/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com