以下是Java 7中的代码编译,但不是openjdk-1.8.0.45-31.b13.fc21.
static void f(Object o1, int i) {}
static void f(Object o1, Object o2) {}
static void test(boolean b) {
String s = "string";
double d = 1.0;
// The supremum of types 'String' and 'double' is 'Object'
Object o = b ? s : d;
Double boxedDouble = d;
int i = 1;
f(o, i); // fine
f(b ? s : boxedDouble, i); // fine
f(b ? s : d, i); // ERROR! Ambiguous
}
Run Code Online (Sandbox Code Playgroud)
编译器声称最后一个方法调用不明确.
如果我们改变的第二个参数的类型f …
public class Primitive {
void m(Number b, Number ... a) {} // widening, autoboxing->widening->varargs
void m(byte b, Number ... a) {} // unboxing, autoboxing->widening->varargs
public static void main(String[] args) {
Byte b = 12;
Primitive obj = new Primitive();
obj.m(b, 23);
}
}
Run Code Online (Sandbox Code Playgroud)
我已经搜索过并发现扩展优先级高于取消装箱,因此在上面的方法调用中,应该调用第一个方法,因为第二个参数对于两者都是相同的.但这不会发生.你可以解释一下吗?
这是一个不编译的代码示例:
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");
}
}
Run Code Online (Sandbox Code Playgroud)
有人能告诉我为什么这些方法含糊不清吗?先感谢您.