为什么 Java 中不允许用 Foo(Object[]) 重载 Foo(Object...)?
我想知道为什么在 Java 中不允许使用 Foo(Object... args)
重载 Foo(Object[] args)
,尽管它们已被使用以不同的方式?
I was wondering why it is not allowed in Java to overload Foo(Object[] args)
with Foo(Object... args)
, though they are used in a different way?
Foo(Object[] args){}
用法如下:
Foo(new Object[]{new Object(), new Object()});
而另一种形式:
Foo(Object... args){}
用法如下:
Foo(new Object(), new Object());
这背后有什么原因吗?
推荐答案
这个 15.12.2.5 选择最具体的方法 讲了这个,但是比较复杂.例如在 Foo(Number... ints) 和 Foo(Integer... ints) 之间进行选择
This 15.12.2.5 Choosing the Most Specific Method talk about this, but its quite complex. e.g. Choosing between Foo(Number... ints) and Foo(Integer... ints)
为了向后兼容,它们实际上是同一件事.
In the interests of backward compatibility, these are effectively the same thing.
public Foo(Object... args){} // syntactic sugar for Foo(Object[] args){}
// calls the varargs method.
Foo(new Object[]{new Object(), new Object()});
例如您可以将 main() 定义为
e.g. you can define main() as
public static void main(String... args) {
<小时>
使它们不同的一种方法是在可变参数之前采用一个参数
A way to make them different is to take one argument before the varargs
public Foo(Object o, Object... os){}
public Foo(Object[] os) {}
Foo(new Object(), new Object()); // calls the first.
Foo(new Object[]{new Object(), new Object()}); // calls the second.
<小时>
它们并不完全相同.细微的区别在于,虽然您可以将数组传递给可变参数,但您不能将数组参数视为可变参数.
They are not exactly the same. The subtle difference is that while you can pass an array to a varargs, you can't treat an array parameter as a varargs.
public Foo(Object... os){}
public Bar(Object[] os) {}
Foo(new Object[]{new Object(), new Object()}); // compiles fine.
Bar(new Object(), new Object()); // Fails to compile.
此外,可变参数必须是最后一个参数.
Additionally, a varags must be the last parameter.
public Foo(Object... os, int i){} // fails to compile.
public Bar(Object[] os, int i) {} // compiles ok.
相关文章