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
137 views
in Technique[技术] by (71.8m points)

Java: "Anonymous" array in for-each-loop

While I was trying something special in for loop I recognized that Java doesn't seem to like putting an anonymous array right as the source for a for-each-loop:

for (String crt : {"a","b","c"} ) {
    doSomething();
}

actually doesn't work while

String[] arr = {"a","b","c"};
for (String crt : arr ) {
    doSomething();
}

does.

Even casting the array to String[] doesn't help. When moving the cursor over the first version, eclipse tells me:

Type mismatch: cannot convert from String[] to String while meaning "crt".

Is this a bug?

question from:https://stackoverflow.com/questions/2358866/java-anonymous-array-in-for-each-loop

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

1 Answer

0 votes
by (71.8m points)

This will work:

for (String crt : new String[]{"a","b","c"} ) {
    doSomething();
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...