为什么Java不允许与美孚(对象[])重载美孚(对象)? [英] Why is it not allowed in Java to overload Foo(Object...) with Foo(Object[])?

查看:135
本文介绍了为什么Java不允许与美孚(对象[])重载美孚(对象)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么它是Java不允许超载美孚(对象[]参数)美孚(对象...参数) ,虽然他们都以不同的方式使用吗?

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

而其他形式的:<​​/ p>

while the other form:

Foo(Object... args){}

使用,如:

Foo(new Object(), new Object());

是否有任何理由背后?

Is there any reason behind this?

推荐答案

此的 15.12.2.5选择最具体的方法谈论这个,但它相当复杂。例如美孚(数...整数)与富之间选择(整数...整数)

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.

此外,一个varags必须是最后一个参数。

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.

这篇关于为什么Java不允许与美孚(对象[])重载美孚(对象)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆