Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For each loop: can we populate an array?

Tags:

java

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.

like image 437
Kifsif Avatar asked Aug 11 '13 07:08

Kifsif


People also ask

Can we use for-each loop in array?

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.

Can you declare an array in a for loop?

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.

Can we use forEach loop for array in Java?

In Java, the for-each loop is used to iterate through elements of arrays and collections (like ArrayList).


1 Answers

From Java Docs,

The for-each loop hides the iterator, so you cannot call remove. Therefore, the for-eachloop 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 wouldcover the great majority of cases.

So, in simple words, its not possible to populate arrays.

like image 168
Vikas V Avatar answered Oct 23 '22 10:10

Vikas V