The code
ArrayList textos = new ArrayList<String>();
textos.add("texto1");
textos.add("texto2");
for (String t : textos) {
System.out.println(t);
}
It’s actually compiled like this:
ArrayList textos = new ArrayList<String>();
textos.add("texto1");
textos.add("texto2");
for (Iterator<String> it = textos.iterator(); it.hasNext();) {
String t = it.next();
System.out.println(t);
}
If I put the statement out, would it look like? So?
ArrayList textos = new ArrayList<String>();
textos.add("texto1");
textos.add("texto2");
String t = it.next();
for (Iterator<String> it = textos.iterator(); it.hasNext();) {
System.out.println(t);
}
Try to compile and see if it works.
Can the compiler be smart enough to find a way to solve this? It can. But they would rather not complicate it for little and debatable advantage.
Of course you can do this:
ArrayList textos = new ArrayList<String>();
textos.add("texto1");
textos.add("texto2");
String t;
for (Iterator<String> it = textos.iterator(); it.hasNext();) {
t = it.next();
System.out.println(t);
}
I put in the Github for future reference.
It’s simple, isn’t it? Think of a more complex example where the compiler would have to parse other snippets of code to know if it’s all right, if it won’t affect anything performing this operation.
Another important point is that the foreach
was created to go from start to end of a data string. It was created to prevent bugs that the programmer could provoke by trying to iterate outside the pattern. Why would you want a specific piece of data - the last one - to escape from the loop? Only the last need could be accessed outside the loop. If you need to do this, better be explicit and put in a variable. It is unlikely that it is worth creating such a complication in the compiler and that it kills one of the advantages of the foreach
to solve a case that is rarely used and can always be avoided.
In the end, it was only a decision made. Nothing prevents language from allowing this. It’s just not worth the effort.
Why is declaration of the variable required Inside a for-each loop in java
– user28595
@bfavaretto the foreach of c# also works like this, like in java. I just haven’t tested if . NET lets you declare out.
– user28595
Another interesting link: http://www.guj.com.br/t/for-foreach-ou-iterator-pq/73747/7
– user28595
If it’s GUJ, it’s not interesting :D Just joking... : P Vini Godoy doesn’t usually talk nonsense, at least he should talk less than me :P In C# there is a discussion for the compiler to generate code that avoids O(N2) in
foreach
nestled. It’s not something simple to do.– Maniero
@bigown do not like much guj, but because of him q referenciei, I have found several posts of him that have clarified many doubts about logic and java.
– user28595