English 中文(简体)
为什么不允许 Java超负荷使用Foo(目标......)?
原标题:Why is it not allowed in Java to overload Foo(Object...) with Foo(Object[])?

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());

是否有理由这样做?

最佳回答

http://java.sun.com/docs/books/jls/third_edition/html/expressions.html#301183”rel=“noreferer”>15.12.2.5 选择最具体的方法就这样说,但很复杂。 e.g. Foo(Number... ints)和Foo(Integer... ints)之间的 Cho

为了落后的兼容,这些实际上是相同的。

public Foo(Object... args){} // syntactic sugar for Foo(Object[] args){}

// calls the varargs method.
Foo(new Object[]{new Object(), new Object()});

例如,你可以将主(主)定义为:

public static void main(String... args) {

使他们不同的方式是,在加拉尔之前就有一个论点。

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.

它们并不完全相同。 微妙的区别是,虽然你能够把一个阵列转至一个堡垒,但你可以把一个阵列参数作为空洞。

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.

此外,var必须是最后的参数。

public Foo(Object... os, int i){} // fails to compile.

public Bar(Object[] os, int i) {} // compiles ok.
问题回答

问题最直接的答案是,如果两项声明都存在,方法研究逻辑就会模糊不清。 如果你在同一级别上宣布,那么在这样说时,就没有办法说明你想要采用的方法:

Object[] a = new Object[10];
Foo(a); // array or vararg?

And Java requires that there always be a most specific method for every method invocation. For the why, see Peter s answer.





相关问题
Spring Properties File

Hi have this j2ee web application developed using spring framework. I have a problem with rendering mnessages in nihongo characters from the properties file. I tried converting the file to ascii using ...

Logging a global ID in multiple components

I have a system which contains multiple applications connected together using JMS and Spring Integration. Messages get sent along a chain of applications. [App A] -> [App B] -> [App C] We set a ...

Java Library Size

If I m given two Java Libraries in Jar format, 1 having no bells and whistles, and the other having lots of them that will mostly go unused.... my question is: How will the larger, mostly unused ...

How to get the Array Class for a given Class in Java?

I have a Class variable that holds a certain type and I need to get a variable that holds the corresponding array class. The best I could come up with is this: Class arrayOfFooClass = java.lang....

SQLite , Derby vs file system

I m working on a Java desktop application that reads and writes from/to different files. I think a better solution would be to replace the file system by a SQLite database. How hard is it to migrate ...

热门标签