<分区>
我进行了一些搜索,但找不到可在 for 循环初始化语句中使用的有效类型列表。是否有可用于 for
循环变量声明的固定类型列表?例如,考虑以下代码:
for (int i = 0; i < 5; i++) // ...
for (String str = "a"; str.length() < 10; str+="a") // ...
第一个有效,但我认为第二个不行。是否有 for 循环初始化中允许的所有类型的列表?
<分区>
我进行了一些搜索,但找不到可在 for 循环初始化语句中使用的有效类型列表。是否有可用于 for
循环变量声明的固定类型列表?例如,考虑以下代码:
for (int i = 0; i < 5; i++) // ...
for (String str = "a"; str.length() < 10; str+="a") // ...
第一个有效,但我认为第二个不行。是否有 for 循环初始化中允许的所有类型的列表?
最佳答案
查看 the for
statement 的 Java 语言规范.您可以在 for
循环中声明和初始化任何类型的变量,甚至可以声明多个变量,只要它们都是同一类型即可。语法中的相关产生式是:
BasicForStatement:
for ( ForInitopt ; Expressionopt ; ForUpdateopt ) Statement
ForInit:
StatementExpressionList
LocalVariableDeclaration
LocalVariableDeclaration:
VariableModifiersopt Type VariableDeclarators
VariableDeclarators:
VariableDeclarator
VariableDeclarators , VariableDeclarator
这意味着您可以执行以下任何操作,例如,
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
那里的第一个例子表明你根本不需要任何变量,并且作为pointed out in the comments ,您也不必有 ForUpdate
。唯一的限制是你必须在中间有一个表达式,它必须是一个 boolean 值表达式。
顺便说一句,ForInit
也可以是一个StatementExpressionList
,这意味着您也可以只执行一些语句,而不是声明和初始化变量。例如,您可以这样做(但这不是一个特别有用的示例):
for ( System.out.println( "beginning loop" ; … ; … )
我想这在模拟 do/while
循环(如果你想这样做)时可能很有用,如果主体是一个简单的函数调用:
for ( method() ; condition ; method() );
关于java - for循环变量声明中允许的类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19341216/