问题
I've done some searches and couldn't find a list of valid types to use in for loop initialization statements. Is there a fixed list of types that can be used in for
loop variable declarations? For instance, consider the following code:
for (int i = 0; i < 5; i++) // ...
for (String str = "a"; str.length() < 10; str+="a") // ...
The first works, but I don't think the second will. Is there a list of all the types which are permitted in a for loop initialization?
回答1:
Have a look at the Java language specification for the for statement. You can declare and initialize any type of variable in a for
loop, and can even declare multiple variables, so long as they're all the same type. The relevant productions in the grammar are:
BasicForStatement:
for ( ForInitopt ; Expressionopt ; ForUpdateopt ) Statement
ForInit:
StatementExpressionList
LocalVariableDeclaration
LocalVariableDeclaration:
VariableModifiersopt Type VariableDeclarators
VariableDeclarators:
VariableDeclarator
VariableDeclarators , VariableDeclarator
This means that you can do any of the following, e.g.,
for ( ; … ; … ) // no variable declaration at all
for ( int i; … ; … ) // variable declaration with no initial value
for ( int i=0; … ; … ) // variable declaration with initial value
for ( int i=0, j=1; … ; … ) // multiple variables
for ( final Iterator<T> it = …; … ; … ) // final variable
The first example there shows that you don't need any variables at all, and as pointed out in the comments, you don't have to have a ForUpdate
either. The only constraint is that you must have an expression in the middle, and it needs to be a boolean valued expression.
As an aside, the ForInit
can also be a StatementExpressionList
, which means that instead of declaring and initializing variables, you can also just execute some statements. E.g, you could do this (but this isn't a particularly useful example):
for ( System.out.println( "beginning loop" ; … ; … )
This could be useful, I suppose, in simulating a do/while
loop (if you wanted to do that), if the body is a simple function call:
for ( method() ; condition ; method() );
回答2:
Second one also will work fine. You can use any type for for loop
for(String str="a";str.length()<10;str+="a")
{
System.out.println(str);
}
I just tried for your scenario and result is
a
aa
aaa
aaaa
aaaaa
aaaaaa
aaaaaaa
aaaaaaaa
aaaaaaaaa
来源:https://stackoverflow.com/questions/19341216/types-permitted-in-for-loop-variable-declarations