Java for each vs regular for -- are they equivalent?
Posted
by polygenelubricants
on Stack Overflow
See other posts from Stack Overflow
or by polygenelubricants
Published on 2010-03-11T05:13:51Z
Indexed on
2010/03/11
5:18 UTC
Read the original article
Hit count: 369
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.
© Stack Overflow or respective owner