重载函数int ...和long ...同时 [英] Overload function int... and long... simultaneously
问题描述
我想创建两个函数,比如说
I want to create two functions, say
long min(long...);
int min(int...);
但是当我尝试调用第二个时,即 min(1,5)
我得到一个模糊的方法调用
But when I try to invoke the second i.e min(1, 5)
one I get ambiguous method call
除重命名外是否有解决方法?
Is there workaround except renaming?
推荐答案
这是一个已知错误
您描述的行为是用Java 7修复的错误。请参阅发行说明中的详细信息,该部分称为大多数特定Varargs方法选择的变化 。
The behaviour you describe is a bug which has been fixed with Java 7. See details in the release notes, section called "Changes in Most Specific Varargs Method Selection".
它应该编译的原因
变量arity排在最后确定最具体的方法。在 JLS 15.12.2.4 - 这是一个摘录:
Variable arity comes last in determining the most specific method. The rules to determine which vararg method applies when there are several are defined in JLS 15.12.2.4 - here is an extract:
一个名为m的变量arity成员方法比另一个变量arity成员方法同名如下:
- [...]
- 一个成员方法有k个参数,另一个有n个参数,其中n≥k ,和:
One variable arity member method named m is more specific than another variable arity member method of the same name if either:
- [...]
- One member method has k parameters and the other has n parameters, where n ≥ k, and:
- 第一种方法的参数类型是U1,...,Uk-1,Uk []。
- 另一种方法的参数类型是T1,...,Tn-1,Tn []。
- 对于来自1的所有j到n,Uj<:Tj
在你的情况下,k = n和 U1 [] = int []
和 T1 [] = long []
所以如果<$ c $可以做出决定c> int< ;: long 或相反。
In your case, k = n, and U1[] = int[]
and T1[] = long[]
so the determination can be made if int <: long
or the opposite.
换句话说,t考虑到的ype不是 int []
与 long []
但是 int
vs long
。并且它发生 int< ;: long
所以应该选择 int ...
方法并且它应该编译。
In other words, the type taken into account is not int[]
vs. long[]
but int
vs long
. And it happens that int <: long
so the int...
method should be chosen and it should compile.
结论:
代码应该(和确实)用Java编译好但是不能用Java 5或6编译。下面的代码用Java 7打印 int
:
The code should (and does) compile fine with Java 7 but would not compile with Java 5 or 6. The code below prints int
with Java 7:
public class Test1 {
public static void main(String[] args) {
new Test1().m(1, 2);
}
int m(int... i) {
System.out.println("int");
return 0;
}
long m(long... i) {
System.out.println("long");
return 0;
}
}
这篇关于重载函数int ...和long ...同时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!