Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
517 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 OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...