[英]In Java, why is the call foo() not ambigious given 2 varags methods foo(int… ints) and foo(Object… objects)?
If I declare just the 2 varargs methods as follows: 如果我只声明2个varargs方法如下:
public void foo(String... strings) {
System.out.println("Foo with Strings");
}
and 和
public void foo(int... ints) {
System.out.println("Foo with ints");
}
and then have the code: 然后有代码:
foo();
this is a compiler error due to the ambiguity as expected. 由于预期的模糊性,这是编译器错误。
However if I have just the following 2 versions of foo: 但是,如果我只有以下2个版本的foo:
public void foo(Object... objects) {
System.out.println("Foo with Objects");
}
and 和
public void foo(int... ints) {
System.out.println("Foo with ints");
}
then the code 那么代码
foo();
calls the ints version of the method. 调用方法的int版本。 Can anyone explain why the second example isn't similarly ambiguous and why it resolves to the int method over the Object method. 任何人都可以解释为什么第二个例子不是同样含糊不清,为什么它解析为Object方法的int方法。 Thanks. 谢谢。
If I recall properly from when I was preparing the scjp, in the first case you have 2 arguments with no relation between them, so the compiler can't choose one. 如果我从准备scjp时正确回忆起来,在第一种情况下你有2个参数,它们之间没有关系,所以编译器不能选择一个。
In the second, with boxing enabled (1.5+), int can be Integer which is a subset of Object, and the compiler, in case of conflict, will always use the most specific definition. 在第二种情况下,启用装箱(1.5+),int可以是Integer,它是Object的子集,如果发生冲突,编译器将始终使用最具体的定义。 So Integer (int) is prioritized. 所以整数(int)是优先的。
Java will always use the closest type possible, so when you pass ints into the method, if you didn't have the int... method, it would autobox them into Integers and use Object.... Since there is an int... method, Java will use that first. Java将始终使用最接近的类型,因此当您将ints传递给方法时,如果您没有int ...方法,它会将它们自动装入Integers并使用Object ....因为有一个int。 ..方法,Java将首先使用它。 This is a choice in the Java compiler design. 这是Java编译器设计中的一个选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.