16

我试过这样的事情:


boolean funkyBoolean = true;
int array[] = funkyBoolean ? {1,2,3} : {4,5,6};

但是这段代码甚至不会编译。对此有什么解释吗?不是 funkyBoolean ? {1,2,3} : {4,5,6} 一个有效的表达?提前致谢!

4

3 回答 3

33

您只能{1, 2, 3}在非常有限的情况下使用该语法,而这不是其中之一。试试这个:

int array[] = funkyBoolean ? new int[]{1,2,3} : new int[]{4,5,6};

顺便说一句,好的 Java 风格是将声明写成:

int[] array = ...

编辑:为了记录,{1, 2, 3}如此受限的原因是它的类型不明确。理论上它可以是一个整数、长整数、浮点数等数组。此外,JLS 定义的 Java 语法禁止它,所以就是这样。

于 2009-11-25T13:07:56.263 回答
6
boolean funkyBoolean = true;
int[] array = funkyBoolean ? new int[]{1,2,3} : new int[]{4,5,6};
于 2009-11-25T13:07:41.117 回答
3

数组初始化器可以在声明中指定,或者作为数组创建表达式(§15.10)的一部分,创建一个数组并提供一些初始值

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 a new int[]{1,2,3} construct, if you want to use the initializer.

于 2009-11-25T13:21:28.887 回答