问题描述
这是一个无法编译的代码示例:
Here's a code example that doesn't compile:
public class Test {
public static void main(String[] args) {
method(1);
}
public static void method(int... x) {
System.out.println("varargs");
}
public static void method(Integer... x) {
System.out.println("single");
}
}
有人能告诉我这些方法含糊不清的原因吗?提前致谢.
Can someone tell me the reason why these methods are ambiguous ? Thank you in advance.
推荐答案
考虑方法签名
public static void foo(int a)
和
public static void foo(Integer a)
在装箱和拆箱之前,调用 foo(1)
不会有歧义.为了确保与早期版本的 Java 兼容,调用保持明确.因此,重载解析的第一阶段不允许装箱、拆箱或变量参数调用,这些都是同时引入的.可变参数调用是指您通过为最后一个参数(而不是数组)传递参数序列来调用可变参数方法.
Before boxing and unboxing, the call foo(1)
would not have been ambiguous. To ensure compatibility with earlier versions of Java, the call remains unambiguous. Therefore the first phase of overload resolution does not allow for boxing, unboxing, or variable arity invocation, which were all introduced at the same time. Variable arity invocation is when you call a varargs method by passing a sequence of parameters for the last argument (rather than an array).
然而,method(1)
为您的方法签名解析允许装箱和拆箱,因为这两种方法都需要一个可变参数调用.由于允许拳击,因此两个签名都适用.通常,当应用两个重载时,会选择最具体的重载.但是,您的签名都没有比另一个更具体(因为 int
和 Integer
都不是另一个的子类型).因此调用 method(1)
是不明确的.
However the resolution of method(1)
for your method signatures allows for boxing and unboxing because both methods require a variable arity invocation. Since boxing is allowed, both signatures apply. Normally when two overloadings apply, the most specific overloading is chosen. However neither of your signatures is more specific than the other (because neither int
nor Integer
is a subtype of the other). Therefore the call method(1)
is ambiguous.
您可以通过传递 new int[]{1}
来进行编译.
You can make this compile by passing new int[]{1}
instead.
这篇关于不明确的可变参数方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!