使用三元运算符初始化数组 [英] Initialize arrays using ternary operator

查看:42
本文介绍了使用三元运算符初始化数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试过这样的事情:



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

但是该代码甚至无法编译。
对此有任何解释吗? 不是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!

推荐答案

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

You can only use the {1, 2, 3} syntax in very limited situations, and this isn't one of them. Try this:

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

好的Java风格是将声明写为:

By the way, good Java style is to write the declaration as:

int[] array = ...

编辑:根据记录, {1、2、3} 如此受限制的原因是其类型不明确。从理论上讲,它可以是整数,longs,floats等的数组。此外,JLS定义的Java语法禁止这样做,就是这样。

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.

这篇关于使用三元运算符初始化数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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