在Java数组初始化 [英] Array initialisation in java

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

问题描述

我注意到,你可以写多个code这样的,这是完全正常的,顺便说一句:

I noticed one could write code like this, which is perfectly normal, by the way:

int arrays[] = {1, 2, 3};
for (int n : arrays)
   System.out.println(n);

但我看不到下面怎么是非法的:

But I don't see how the following is illegal:

for (int n : {1, 2, 3})
   System.out.println(n);

从一个编译器作者的角度来看,这不会引入任何含糊之处,不是吗?类型的阵列可以预期是相同类型的元素声明previously。换句话说, N 声明为 INT ,以使阵列的必须的是 INT []

From a compiler writer's point of view, this does not introduce any ambiguity, does it? The type of the array can be expected to be the same type as the element declared previously. In other words, n is declared as int, so the array must be int[]

推荐答案

您需要语法如下:

for(int n : new int[]{1, 2, 3})
   System.out.println(n);

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

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