Varargs Java模糊呼叫 [英] Varargs Java Ambiguous Call
问题描述
我对Java的 varargs 方法感到有些困惑:
I'm a little confused about Java's varargs methods:
public static int sum(int ...a) {
return 0;
}
public static double sum(double ...a) {
return 0.0;
}
当我试图调用 sum()
不传递任何参数,然后调用 int
版本的方法。我不明白为什么;通常,编译器必须引发错误。
When I tried to invoke sum()
without passing any argument, then the int
version of method was invoked. I don't understand why; normally the compiler must raise an error.
相反,当我尝试调用 sum $时,以下代码会生成编译器错误c $ c>没有任何参数:
By contrast, the following piece of code generates a compiler error when I try to invoke sum
without any argument:
public static int sum(int ...a) {
return 0;
}
public static boolean sum(boolean ...a) {
return true;
}
推荐答案
此处适用的一般规则是这样的:如果一个方法签名严格更具体,那么Java选择它没有错误。
The general rule that applies here is this: if one method signature is strictly more specific than the other, then Java chooses it without an error.
直接,方法签名更具体的是,如果你可以完全删除它,另一个不太具体的那个适用于每个现有的调用。
Intuituively, a method signature is more specific if you could delete it entirely and the other, less specific one would be applicable to each existing invocation.
当在签名<$ c之间进行选择时$ c> sum(int ... args)和 sum(double ... args)
,签名总和(int ... args)
更具体,因为该方法的任何调用也可以传递给 sum(double ... args)
通过应用扩大转换。同样不适用于 sum(boolean ... args)
方法,该方法无法进行类似转换。
When presented with a choice between the signatures sum(int... args)
and sum(double... args)
, the signature sum(int... args)
is more specific because any invocation of that method could also be passed on to sum(double... args)
by applying a widening conversion. The same does not hold for a sum(boolean... args)
method, which cannot be similarly converted.
Java语言规范,SE 8版本:
Java Language Specification, SE 8 version:
15.12。方法调用表达式
15.12.2.5。选择最具体的方法
Java编程语言使用选择最具体方法的规则。
...
对于带参数表达式e1的调用,一个适用的方法m1比另一个适用的方法m2更具体, ...,ek,如果满足以下任何条件:
One applicable method m1 is more specific than another applicable method m2, for an invocation with argument expressions e1, ..., ek, if any of the following are true:
...
- m2不是通用的,m1和m2适用于严格或松散的调用,并且m1具有形式参数类型S1,...,Sn和m2具有形式参数类型T1,...,Tn,对于所有i(1≤i≤n,n = k),对于参数ei,类型Si比
更具体。
- m2 is not generic, and m1 and m2 are applicable by strict or loose invocation, and where m1 has formal parameter types S1, ..., Sn and m2 has formal parameter types T1, ..., Tn, the type Si is more specific than Ti for argument ei for all i (1 ≤ i ≤ n, n = k).
...
如果S<:T(§4.10),则类型S比任何表达式的类型T更具体。
A type S is more specific than a type T for any expression if S <: T (§4.10).
4.10。子类型
4.10.1。原始类型之间的子类型
double> 1 float
4.10. Subtyping
4.10.1. Subtyping among Primitive Types
double >1 float
float> 1 long
float >1 long
long> 1 int
long >1 int
这篇关于Varargs Java模糊呼叫的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!