使用三元运算符初始化数组
我尝试过这样的事情:
boolean funkyBoolean = true;
int array[] = funkyBoolean ? {1,2,3} : {4,5,6};
但是这段代码甚至无法编译。 对此有什么解释吗? 不是 funkyBoolean 吗? {1,2,3} : {4,5,6}
是一个有效的表达式吗? 提前致谢!
i tried something like this:
boolean funkyBoolean = true;
int array[] = funkyBoolean ? {1,2,3} : {4,5,6};
But this code won't even compile.
Is there any explanation for this? isn't funkyBoolean ? {1,2,3} : {4,5,6}
a valid expression?
thank's in advance!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您只能在非常有限的情况下使用
{1, 2, 3}
语法,而这不是其中之一。试试这个:顺便说一句,好的 Java 风格是将声明编写为:
编辑:根据记录,
{1, 2, 3}
受到如此限制的原因是它的类型不明确。理论上它可以是整数、长整型、浮点数等的数组。此外,JLS 定义的 Java 语法禁止它,所以就是这样。You can only use the
{1, 2, 3}
syntax in very limited situations, and this isn't one of them. Try this:By the way, good Java style is to write the declaration as:
EDIT: For the record, the reason that
{1, 2, 3}
is so restricted is that its type is ambiguous. In theory it could be an array of integers, longs, floats, etc. Besides, the Java grammar as defined by the JLS forbids it, so that is that.这就是 Java 规范 说 (10.6)。因此,“短”版本(带有创建表达式)仅允许在声明中使用 (
int[] a = {1,2,3};
),在所有其他情况下,您需要一个new int[]{1,2,3}
构造,如果你想使用初始化器。That's what the Java Spec says (10.6). So the 'short' version (with the creation expression) is only allowed in declarations (
int[] a = {1,2,3};
), in all other cases you need anew int[]{1,2,3}
construct, if you want to use the initializer.