Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
456 views
in Technique[技术] by (71.8m points)

Array initialisation in 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);

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[]

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You need this syntax:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...