Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java for each vs regular for -- are they equivalent?

Are these two constructs equivalent?

char[] arr = new char[5];
for (char x : arr) {
    // code goes here
}

Compared to:

char[] arr = new char[5];
for (int i = 0; i < arr.length; i++) {
    char x = arr[i];
    // code goes here
}

That is, if I put exactly the same code in the body of both loops (and they compile), will they behave exactly the same???


Full disclaimer: this was inspired by another question (Java: are these 2 codes the same). My answer there turned out not to be the answer, but I feel that the exact semantics of Java for-each has some nuances that needs pointing out.

like image 386
polygenelubricants Avatar asked Mar 11 '10 05:03

polygenelubricants


People also ask

What is difference between for and forEach in Java?

The for loop is a control structure for specifying iteration that allows code to be repeatedly executed. The foreach loop is a control structure for traversing items in an array or a collection. A for loop can be used to retrieve a particular set of elements.

Is a for-each loop more efficient?

The forloop is faster than the foreach loop if the array must only be accessed once per iteration.

What is the advantage of using forEach over traditional for loop?

The forEach() method provides several advantages over the traditional for loop e.g. you can execute it in parallel by just using a parallel Stream instead of a regular stream. Since you are operating on stream, it also allows you to filter and map elements.

Is forEach faster than for Java?

Foreach performance is approximately 6 times slower than FOR / FOREACH performance. The FOR loop without length caching works 3 times slower on lists, comparing to arrays. The FOR loop with length caching works 2 times slower on lists, comparing to arrays.

What is the difference between for and for each loop in Java?

Difference between For and For-each Loop in Java. Termination of this traditional loop is controlled by loop condition. Therefore, For loop executes repeatedly until the given condition turns out to be false. The iteration variable in foreach is read-only.

What is the difference between == and equals in Java?

Both equals () method and the == operator are used to compare two objects in Java. == is an operator and equals () is method. But == operator compares reference or memory location of objects in a heap, whether they point to the same location or not.

What is the difference between for and for/of in JavaScript?

With for and for/in, you need to print out arr [i]: With the other two constructs, forEach () and for/of, you get access to the array element itself. With forEach () you can access the array index i, with for/of you cannot. JavaScript arrays are objects. That means you can add string properties to your array, not just numbers.

How to compare two strings in Java?

In Java, the String equals () method compares the two given strings based on the data/content of the string. If all the contents of both the strings are the same, it returns true. If all characters are not matched, then it returns false.


1 Answers

While often the two constructs are interchangeable, THEY ARE NOT 100% EQUIVALENT!!!

A proof can be constructed by defining // code goes here that would cause the two constructs to behave differently. One such loop body is:

arr = null;

Therefore, we are now comparing:

char[] arr = new char[5];
for (char x : arr) {
    arr = null;
}

with:

char[] arr = new char[5];
for (int i = 0; i < arr.length; i++) {
    char x = arr[i];
    arr = null;
}

Both code compiles, but if you run them, you will find that the first loop terminates normally, while the second loop will throw a NullPointerException.

This means that they are not 100% equivalent! There are scenarios where the two constructs will behave differently!

Such scenarios are likely to be rare, but this fact should not be forgotten when debugging, because otherwise you might miss some really subtle bugs.


As an addendum, note that sometimes the for-each construct is not even an option, e.g. if you need the index. The crucial lesson here is that even if it's an option, you need to make sure that it's actually an equivalent substitute, because it's not always guaranteed

Similarly, if you start with a for-each loop and later realized that you need to switch to the indexed for loop, make sure that you're preserving the semantics, because it's not guaranteed.

In particular, _be wary of any modification to the reference of the array/collection being iterated_ (modification to the content may/may not trigger ConcurrentModificationException, but that's a different issue).

Guaranteeing semantics preservation is also a lot more difficult when you use collections that use custom iterators, but as this example shows, the two constructs are different even when simple arrays are involved.

like image 56
polygenelubricants Avatar answered Oct 23 '22 01:10

polygenelubricants