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?

share|improve this question

2  
Regarding "Is this a bug?": catb.org/~esr/faqs/smart-questions.html#id382249 – Joachim Sauer Mar 1 '10 at 20:32
I don't actually claim to have found a bug. I just ask whether it could be a bug. And it's strange that in one part this type of expression works and in another it doesn't. Not very consistent in my eyes. – Atmocreations Mar 1 '10 at 20:48
feedback

4 Answers

up vote 15 down vote accepted

This will work:

for (String crt : new String[]{"a","b","c"} ) {
    doSomething();
}
share|improve this answer
Accept: Shortest answer which provides a correct solution. Thanks! – Atmocreations Mar 1 '10 at 21:01
feedback

The Java language provides the {"a","b","c"} form as a shortcut, but it is only possible during assignment. It's possible this is to avoid possible ambiguities during parsing, in some positions {} could be interpreted as a code block.

The right way to do it would be how noah suggests, with new String[]{"a","b","c"}.

share|improve this answer
4  
Please note that that short form isn't allowed in all assignments. It is allowed only in initializations. – Joachim Sauer Mar 1 '10 at 20:54
@Joachim: interesting fact. This pretty much solves my question, thanks for pointing it out. @Tom Castle: +1 Good answer – Atmocreations Mar 1 '10 at 20:58
feedback

Dunno, what about this? :) Pity there's no succinct version. Suppose you could use Groovy or Scala if you wanted anything like that :)

for (String s : Arrays.asList("a","b","c")) {
    hmm(s);
}
share|improve this answer
sounds a bit like C# :P – Atmocreations Mar 1 '10 at 20:47
feedback

You want

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

I use IntelliJ and it says put the message "expression expected" on the right-hand side of the colon in the for-loop, which seems more accurate.

I should add that IntelliJ also offers to add the "new String []" automagically for me.

share|improve this answer
feedback

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.