为什么数组常量只能用于初始值设定项? [英] Why can array constants only be used in initializers?

查看:175
本文介绍了为什么数组常量只能用于初始值设定项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

数组常量只能用于初始值设定项错误

我正在研究数组,我通过这种在一行中声明和初始化数组的简短方法。例如,

I was studying arrays, and I came through this short-cut method of declaring and initializing an array in one line. For example,

int[] a = {1, 2, 3, 4, 5};

但是当我尝试执行以下代码时,我得到了这个编译错误,说数组常量只能是在初始化程序中使用。

But when I tried to do following code, I got this compiler error saying "Array constants can only be used in initializer".

int[] a;
a = {1, 2, 3, 4};

为什么会这样?

推荐答案

这是不允许的,因为 JLS说所以。语法仅在声明和数组创建表达式中允许。

It's not allowed because the JLS says so. The syntax is only permitted in declarations and in array creation expressions.

后者提供了另一种实现相同结果的方法:

The latter provide an alternative way of achieving the same result:

int[] a;
a = new int[]{1, 2, 3, 4};

至于要求新T []的实际根本原因,我的猜测如下。考虑以下数组初始值设定项:

As to the actual underlying reason for requiring the new T[], my guess is as follows. Consider the following array initializer:

{1, 2, 3, 4}

它可用于初始化不同类型的数组:

It can be used to initialize arrays of different types:

new int[]{1, 2, 3, 4};
new float[]{1, 2, 3, 4};
new double[]{1, 2, 3, 4};

如果新T [] 位不是不,我怀疑裸 {1,2,3,4} 可能会在语义分析过程中造成困难。在这里,我正在考虑以下情况:

If the new T[] bit wasn't required, I suspect that the bare {1, 2, 3, 4} could cause difficulties during semantic analysis. Here, I am thinking about cases like:

void f(float[] x) { ... }
void f(double[] x) { ... }
void g() {
  f({1, 2, 3, 4});
}

如果允许这种语法,语言规范必须处理复杂性选择要调用哪个函数。

If this syntax were allowed, the language spec would have to deal with the complexity of choosing which function to call.

同样,还不清楚 {null} 。它可以是 Object [] Integer [] Serializable [] 依此类推。

In a similar vein, it's not clear what should be the type of {null}. It can be Object[], Integer[], Serializable[] and so on.

最后,空数组 {} 将是最棘手的。在这里,我们甚至无法判断它是一个对象数组还是一组标量。

And finally, the empty array {} would be the trickiest of all. Here, we can't even tell if it's an array of objects or an array of scalars.

而不是处理所有这些复杂性,语言设计师似乎选择了通过要求 new T [] 语法来避免它们。

Instead of dealing with all these complexities, it seems that the language designers chose to avoid them by requiring the new T[] syntax.

这篇关于为什么数组常量只能用于初始值设定项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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