views:

221

answers:

3

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.

+13  A: 

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.

polygenelubricants
I would have immediately, blithely and wrongly said "yes, they're completely equivalent because the 2nd form is just syntactic sugar for the first." Well done on pointing out this subtle distinction!
Carl Smotricz
Thank you for taking the time to read this. I hope other people would do the same instead of downvoting on a whim.
polygenelubricants
Very excellent answer, polygenelubricants (+1). Like Carl, I hadn't realized that this subtle difference existed. Thank you for pointing it out. You may also want to add to your answer the fact that the second will let you access the index which is needed in some cases.
JasCav
I've made some improvements to the answer. Feel free to suggest anything else that needs to be addressed.
polygenelubricants
Excellent, I would have never thought of that, upvoted.
fastcodejava
+1, nice answer
Rakesh Juyal
+1  A: 

The first one is more readable and so more preferable, if you're going to need the index anyway then plump for the second.

Tom
+1  A: 

They are pretty much equivalent. But there can be few cases where they are not. It is best to make it final.

final char[] arr = new char[5];   // Now arr cannot be set null as shown 
                                  // in above answer.

Even then you can do i-- in the second loop. If you don't do some these unlikely things they are mostly equivalent.

fastcodejava
True on the `i--`, but that code wouldn't be transplantable to the for-each anyway, because it would throw a compile-time error. Still, +1 on `final`. Always a good thing whenever applicable.
polygenelubricants