The following works fine,
int i;
for (i = 0; i < 10; i++) {}
But this doesn't
// a is an ArrayList of Integers
Integer i;
for (i: a) {}
and I'm forced to do it this way:
for (Integer i : a) {}
Why is it that the second loop doesn't work?
Think about it this way: What would happen if you always initialized your variable?
In the first case: It's initialized IN this example, clearly no problem.
In the second case: You initialize it, to say, 1. Now you have a variable, "1", and you throw it into this for loop. "for( 1 : a)". What does that mean?? And if you override the value of "i" for every value in a, then when it comes out of the loop it's simply the last entry in A. Again, what does that really mean? Why would that be useful? How does the effect the rest of the code outside of this loop? It's bad design to support that, it would result in all sorts of crazy, unexpected behavior and unreadable code.
In the third case: Your variable is explicitly declared IN the scope of that loop, and is very clearly temporary. It will do its job of extracting what you need from this array and be done with. Any modifications to outside pieces of code will need to happen intentionally with explicit setters. Note that you can't initialize it here, because initializing is meaningless.
For the for loops, you need 3 statements.
Your second loop only has 2 statements, and your first one has 3. On top of that, you never initialized your integer i. Make sure to do
int i =0;
for(i;i<=10;i++){
}
For enchanced for loops, you must have
for (String element : array) {
System.out.println("Element: " + element);
}
You can check out this link, it might help. What is the syntax of enhanced for loop in Java?
You have to explicitly give the type of object that you are iterating over in the array list. In the first for loop you are just plugging in the index. In the second, you are trying to have the for loop grab the object without knowing what kind of object it is.
The enhanced for statement is equivalent to a basic for statement of the form:
for (Iterator i = Expression.iterator(); i.hasNext(); ) {
TargetType Identifier = (TargetType) i.next();
...
}
14.14.2. The enhanced for statement
This one is normal for loop using. You can declare the variable type outside the for
int i;
for (i = 0; i < 10; i++) {}
or
Integer i;
for (i = 0; i < 10; i++) {
System.out.println(i);
}
the second one, if you would like to use foreach(also known as Enhanced For-loop) with the Generic type, the syntax must be:
for(data_type variable : array | collection){}
Hope this help!
As per JLS (see very bottom of 15.27.2. Lambda Body) - in each iteration of enhanced-for loop we have a brand-new i variable => we cannot reuse (Integer i;) variable declared before the loop.
We have a brand-new variable in each loop, hence we have declaration syntax here: for(Integer i : array) as it is really declared again and again on each iteration.
Proof comes from JLS code example about lambdas:
void m9(String[] arr) {
for (String s : arr) {
foo(() -> s);
// Legal: s is effectively final
// (it is a new variable on each iteration)
}
}
Related
I was surprised to read in Cay Horstmann's Java 9 book, that memory is allocated each time to the temporary, in an enhanced for loop:
"a new variable arg is created in each iteration" (Chap 3, page 126)
for(String arg:args) {
...
}
I always thought the compiler would allocate the space for a local variable in a loop, before entering the loop, to optimize performance.
Why would the variable be created each time?
This question was asked before in the context of C, but not for Java. I am asking for a loop in general, not just this case.
for (String s : ...) { }
double x;
for (int i : ...) {
long n; ...
}
double y;
For the above the compiler will declare 5 variable slots on the call stack, which can be overlapping (x sharing the memory with s). The needed stack size is added to the method, so stackoverflow can be checked.
Only any assignment, like object creation, is repeated inside the loop.
However that is as needed. A beginner's error is:
List<A> list = new ArrayList<>();
A obj = new A(); // *** ERROR ***
for (...) {
obj.name = ...;
list.add(obj);
}
Filling the list with the same object instance whose fields are of the last loop step.
A repeated creation of say n is not done. It is certainely no optimisation to place the declaration outside the for-loop on a call - on the contrary: the variable slot on the stack remains after the loop.
I read on http://www.leepoint.net/notes-java/flow/loops/foreach.html. the for each equivalent to
for (int i = 0; i < arr.length; i++) {
type var = arr[i];
body-of-loop
}
is
for (type var : arr) {
body-of-loop
}
My question is how does a for each loop work for an empty list. I know for the regular for loop, the arr.length will just evaluate to 0 and the loop wont execute. What about the for each loop?
My question is how does a for each loop work for an empty list
ForEach also works in the same way. If the length is zero then loop is never executed.
The only difference between them is use ForEach loop when you want to iterate all the items of the list or array whereas in case of normal for loop you can control start and end index.
It uses the iterator of the Iterable collection, e.g. List. It is the duty of the implementer of the Iterator to write the hasnext() method to return false if there is no next item which will be the case if the collection is empty
Yes, it is equivalent.
If the list is empty, the for-each cycle is not executed even once.
As #user3810043 alludes to in their answer comments, the enhanced for statement is literally evaluated the same as an equivalent basic for statement:
14.14.2. The enhanced for statement
...
The type of the Expression must be a subtype of the raw type Iterable or an array type (§10.1), or a compile-time error occurs.
...
Otherwise, the Expression necessarily has an array type, T[].
Let L1 ... Lm be the (possibly empty) sequence of labels immediately
preceding the enhanced for statement.
The enhanced for statement is equivalent to a basic for statement of
the form:
T[] #a = Expression;
L1: L2: ... Lm:
for (int #i = 0; #i < #a.length; #i++) {
{VariableModifier} TargetType Identifier = #a[#i];
Statement
}
#a and #i are automatically generated identifiers that are distinct from any other identifiers (automatically generated or otherwise) that are in scope at the point where the enhanced for statement occurs.
^ Quote from The Java® Language Specification
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 forloop?
In short the questions:
Is i the copy of each element of the array? If not what is it
then?
Isn't the foreach loop slower then the common one? If not, how
"badly" is then operator[] designed?
There is nothing more except readability to win in a foreach loop?
In the code
for (int i: array){
You declare a variable i that on each loop iteration gets the value of the next element in the array, it isn't a reference to that element.
In
i = 1;
you assign a new value to the variable, not to the element in the array.
You cannot set the values of array elements with a foreach loop directly. Use a normal for loop for that
for (int i = 0; i < array.length; i++) {
array[i] = ...; // some value
}
In the above example, you are using the declared variable i as an index to the element in the array.
array[i]
is accessing the element itself whose value you can modify.
Ans obviously failed to assign 1 to every element of the array. The I
added System.out.print(i); 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)
You must have put the System.out.print(i) after the i = 1, otherwise you would get 0000000.
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?
Have a look here to see how the foreach loop works. For arrays,
for (int i: array){
i = 1;
}
is equivalent to
for (int index = 0; index < array.length; index++) {
int i = array[index];
i = 1;
}
So it isn't slower. You're doing one more primitive creation on the stack.
It depends on the implementation. For arrays, it's not slower in any way. It just serves different purposes.
why one would use an obviously slower foreach loop instead of a common
forloop?
One reason is for readability. Another is when you don't care about changing the element references of the array, but using the current references.
Take a reference type example
public class Foo {
public int a;
}
Foo[] array = new Foo[3];
for (int i = 0; i < array.length; i++) {
array[i] = new Foo();
array[i].a = i * 17;
}
for (Foo foo : array) {
foo.a = 0; // sets the value of `a` in each Foo object
foo = new Foo(); // create new Foo object, but doesn't replace the one in the array
}
With primitive types such a thing doesn't work.
for (int index = 0; index < array.length; index++) {
int i = array[index];
i = 1; // doesn't change array[index]
}
From Item 46 in Effective Java by Joshua Bloch :
The for-each loop, introduced in release 1.5, gets rid of the clutter
and the opportunity for error by hiding the iterator or index variable
completely. The resulting idiom applies equally to collections and
arrays:
// The preferred idiom for iterating over collections and arrays
for (Element e : elements) {
doSomething(e);
}
When you see the colon (:), read it as “in.” Thus, the loop above
reads as “for each element e in elements.” Note that there is no
performance penalty for using the for-each loop, even for arrays. In
fact, it may offer a slight performance advantage over an ordinary for
loop in some circumstances, as it computes the limit of the array
index only once. While you can do this by hand (Item 45), programmers
don’t always do so.
Advantages
Readability
It increases the abstraction level - instead of having to express the low-level details of how to loop around a list
or array (with an index or iterator), the developer simply states that
they want to loop and the language takes care of the rest.
Disadvantage:
Cannot access the index or to remove an item.
To sum up,
the enhanced for loop offers
A concise higher level syntax to loop over a list or array which
1.1 improves clarity
1.2 readability.
However, it misses : allowing to access the index loop or to remove an item.
Setting the values by reference didn't work because int is a primitive type. For any kind of Object[] it would work. Making a copy of a primitive type is very fast, and will be done by the processor many times without your realising.
The foreach loop is more readable, but it's also more writeable. A common programmer error is:
for (int i = 0; i < 10; i++)
{
for(int j = 0; j < 10; i++) //oops, incrementing wrong variable!
{
//this will not execute as expected
}
}
It's impossible to make this error using a foreach loop.
The for statement also has another form designed for iteration through Collections and arrays This form is sometimes referred to as the enhanced for statement, and can be used to make your loops more compact and easy to read.
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html
So, you're right. Readability is the main win here. For further information on the for each loop, or enhanced for loop, here a blog entry from oralce.
The for each utilized the functionality of the Iterable<E> interface, so the performance depends on the implementation.
Can anyone explain this code to me?
class className {
int[] coeffs;
int count(int value) {
int count = 0;
for (int coeff: coeffs)
if (coeff == value)
count++;
return count;
}
}
What I really don't understand is this part:
for (int coeff: coeffs)
What is it mean? Thanks for help.
In earlier versions of Java, there was only the C/Fortran style "for()" loop.
Java 5 (JDK 1.5, 2004) introduced a "foreach()" loop, with the syntax you've described:
http://en.wikipedia.org/wiki/Foreach_loop#Java
for (type item: iterableCollection) {
// do something to item
}
It's worth noting that although the newer "foreach" syntax might be more "elegant", the "old" for loop index can actually be faster:
https://www.java.net//node/662136
That is the enhanced for each loop to loop through the array int[] array.
Look at the Oracle documentation
This is a foreach loop - it means that for every value in the array coeffs the code inside the for loop will be executed, with the variable coeff representing the value used during that particular iteration.
That's an enhanced for loop. It is structured as follows:
for(Object o: collection)
Basically, objects is an array of objects or primitive, or an Iterable of objects.
Java will iterate over the array or Iterable, set o to the object/value retrieved, and process the block. It allows for quick iteration without dealing with handling your own iterators/
If there is a method call MyClass.returnArray() and I iterate over the array using the for-each construct (also called the "enhanced for" loop):
for (ArrayElement e : MyClass.returnArray()) {
//do something
}
will then the returnArray() method be called for every iteration?
No, it won't. The result of the first call will be stored in the compiled code in a temporary variable.
From Effective Java 2nd. Ed., Item 46:
Note that there is no performance penalty for using
the for-each loop, even for arrays. In fact, it may offer a slight performance advantage
over an ordinary for loop in some circumstances, as it computes the limit of
the array index only once.
From the java language spec:
EnhancedForStatement:
for ( VariableModifiersopt Type Identifier: Expression) Statement
and later on:
T[] a = Expression;
L1: L2: ... Lm:
for (int i = 0; i < a.length; i++) {
VariableModifiersopt Type Identifier = a[i];
Statement
}
This is (in pseudo code) the equivalent of the advanced for loop for arrays. And it is made clear, that the Expression is evaluated once and the resulting array is assigned to T[] a.
So it's perfectly safe to use even complex expressions in the advanced for loop statement.
No.
The for loop is just syntactic sugar. It behaves differently depending on whether or not it is applied to an Array argument or an object implementing the Iterable interface.
For Iterable objects, the loop expands to something like this:
Iterator<ArrayElement> iter = iterableObject.iterator();
while (iter.hasNext()) {
ArrayElement e = iter.next();
// do smth
}
What your example code is actually doing is something like this:
Object[] temp = Method.returnArray();
for ( int i = 0; i < temp.length; i++ ) {
ArrayElement e = (ArrayElement) temp[i];
// do smth
}
No, it will be called once. It's not like the termination condition of a standard for loop, which gets evaluated on every iteration.