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?
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.
The foreach loop works only on arrays, and is used to loop through each key/value pair in an array.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With