Why is it not allowed in Java to overload Foo(Object...) with Foo(Object[])?(为什么 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.
这篇关于为什么 Java 中不允许用 Foo(Object[]) 重载 Foo(Object...)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么 Java 中不允许用 Foo(Object[]) 重载 Foo(Object...)?


- C++ 和 Java 进程之间的共享内存 2022-01-01
- Safepoint+stats 日志,输出 JDK12 中没有 vmop 操作 2022-01-01
- 如何使用WebFilter实现授权头检查 2022-01-01
- 将log4j 1.2配置转换为log4j 2配置 2022-01-01
- 从 finally 块返回时 Java 的奇怪行为 2022-01-01
- Java包名称中单词分隔符的约定是什么? 2022-01-01
- Eclipse 插件更新错误日志在哪里? 2022-01-01
- value & 是什么意思?0xff 在 Java 中做什么? 2022-01-01
- Jersey REST 客户端:发布多部分数据 2022-01-01
- Spring Boot连接到使用仲裁器运行的MongoDB副本集 2022-01-01