I can read data from an array with for each syntax:
int[] a = new int[100];
for (int i = 0; i < 100; i++){
a[i] = i;
}
for (int element : a){
System.out.println(element);
}
But is it possible to populate the array likewise. Say, with i*2
values?
I failed to invent such a method and would rather ask you whether I'm wrong or not.
The forEach method is also used to loop through arrays, but it uses a function differently than the classic "for loop". The forEach method passes a callback function for each element of an array together with the following parameters: Current Value (required) - The value of the current array element.
You can declare (define) an array inside a loop, but you won't be able to use it anywhere outside the loop. You could also declare the array outside the loop and create it (eg. by calling new ...) inside the loop, in which case you would be able to use it anywhere as far as the scope the declaration is in goes.
In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList).
From Java Docs,
The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-each
loop is not usable for filtering. Similarly it is not usable for loops where you need to replace elements in a list or array as you traverse it. Finally, it is not usable for loops that must iterate over multiple collections in parallel. These shortcomings were known by the designers, who made a conscious decision to go with a clean, simple construct that would
cover the great majority of cases.
So, in simple words, its not possible to populate arrays.
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