Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 820
Atmocreations Avatar asked Mar 01 '10 20:03

Atmocreations


People also ask

Can we create anonymous array in Java?

We can create an array without a name. Such types of nameless arrays are called anonymous arrays. The main purpose of an anonymous array is just for instant use (just for one-time usage). An anonymous array is passed as an argument of a method.

DO forEach loops work with arrays?

The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.

Can you forEach in array Java?

The forEach in JavaThe foreach loop is generally used for iteration through array elements in different programming languages. The Java provides arrays as well as other collections and there should be some mechanism for going through array elements easily; like the way foreach provides.


1 Answers

This will work:

for (String crt : new String[]{"a","b","c"} ) {     doSomething(); } 
like image 121
noah Avatar answered Sep 28 '22 09:09

noah