I just started learning Java and the first thing I came across is the foreach
loop, not knowing the way it works the first thing I did was:
int[] array = new int [10];
for (int i: array){
i = 1;
}
And obviously failed to assign 1
to every element of the array. Then I added System.out.print(i);
(after i = 1;
) to the body of the loop and saw that the output of the screen was 1111111111
but since doing something with i
inside the loop is valid that most likely i
is a copy of every element of the array, ain't it? (first questions)
If the above is true doesn't this mean that the foreach
loop is much slower then the common for loop since it involves making copies of each element of the array? Or since Java
doesn't have pointers and pointer arithmetic, the oprator[]
may be designed in some other "badly" fashion that copying every element is actually faster?
And if the above assumptions are true, why one would use an obviously slower foreach
loop instead of a common for
loop?
In short the questions:
Is
i
the copy of each element of thearray
? If not what is it then?Isn't the
foreach
loop slower then the common one? If not, how "badly" is thenoperator[]
designed?There is nothing more except readability to win in a
foreach
loop?