java中的数组初始化 [英] Array initialisation in java

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

问题描述

顺便说一句,我注意到有人可以写出这样的代码,这很正常:

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);

从编译器作者的角度来看,这不会引入任何歧义,是吗?可以预期数组的类型与之前声明的元素的类型相同.换句话说,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天全站免登陆