在 Java 中,为什么这个语法有效而这个无效?
我知道这两者都是有效的,并且含义完全相同:
首选:
void foo(int[] bar){
// do something
}
不首选:
void foo(int bar[]){
// do something
}
我不明白的是,遵循与上面相同的逻辑,为什么这无效?
void foo(int... bar[]){
// do something
}
但这是:
void foo(int[]... bar){
// do something
}
I understand that both of these are valid and mean the exact same thing:
Preferred:
void foo(int[] bar){
// do something
}
Not preferred:
void foo(int bar[]){
// do something
}
What I don't understand is, following the same logic as above, why is this not valid?
void foo(int... bar[]){
// do something
}
But this is:
void foo(int[]... bar){
// do something
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(2)
悲凉≈2025-01-22 14:21:32
在Java中,确实可以用两种形式声明数组,例如
int[] arr;
or 。
int arr[];
第二种形式通常不是首选,因为括号标识数组类型并且应该与类型名称一起出现。简而言之,您可以
type variable;
使用第一个数组使用模型来遵循所有代码的形式约定。
现在回到问题,这正是不支持以 int...arr[]
形式使用 varargs
的原因。 varargs
指定特定类型的任意计数性质。
因此,使用类型规范 int...
表示任意数量的整数值,而 int[]...
表示任意数量的整数数组。 varargs
支持将变量用作其类型而不是数组。所以 int... arr[]
是一个错误。
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
让我们从
int bar[]
与int[] bar
开始。前者是原始 Java 1.0 中包含的一些语法糖,供从 C 或 C++ 过渡的程序员使用。它对 Java 语法来说有点“疣”……现在大多数人认为一开始支持它就是一个错误。而且规范本身、教程、书籍和……Java 风格检查器都不鼓励您使用它。因此,在 Java 的发展后期(在 Java 5 中),他们添加了
...
语法来支持方法调用中的“varargs”功能。好的。但它们不包括对句法疣的支持。为什么?
int... bar[]
在视觉上是不明确的1。它是“int 数组的可变参数”还是“int 可变参数的数组”?即使 C 和 C++ 也不允许您编写int[] bar[]
,这大致就是它所映射的内容。void foo(int... bar[])
看起来令人讨厌。1 - 也许实际上并不含糊,因为“int varargs 数组”解释没有意义。然而,这并不能避免假设语法可能引起的混乱。最好避免这个问题......就像他们所做的那样。
Let's start with
int bar[]
versusint[] bar
. The former is some syntactic sugar included in the original Java 1.0 for programmers transitioning from C or C++. It is a bit of a "wart" on the Java syntax ... and most people now think it was a mistake to support it in the first place. And you are discouraged from using it by the spec itself, tutorials, books and ... Java style checkers.So later in the evolution of Java (in Java 5) they added the
...
syntax to support "varargs" functionality in method calls. Nice. But they didn't include support for the syntactic wart.Why?
int... bar[]
is visually ambiguous1. Is it a "varags of arrays of int" or an "array of varargs of int"? Even C and C++ will not allow you to writeint[] bar[]
, which is roughly what this maps to.void foo(int... bar[])
looks nasty.1 - Maybe not actually ambiguous, since the "array of varargs of int" interpretation doesn't make sense. However, that is not going to avoid the confusion that the hypothetical syntax would cause. Best to avoid the problem ... like they did.