Java for each vs regular for -- are they equivalent?
- by polygenelubricants
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.