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.
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.
The forloop is faster than the foreach loop if the array must only be accessed once per iteration.
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.
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.
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.
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.
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.
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.
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.
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