Tof*_*eer 51
for(int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}
Run Code Online (Sandbox Code Playgroud)
要么
for(String value : array)
{
System.out.println(value);
}
Run Code Online (Sandbox Code Playgroud)
第二个版本是"for-each"循环,它适用于数组和集合.大多数循环可以使用for-each循环完成,因为您可能不关心实际索引.如果您确实关心实际索引我们的第一个版本.
为了完整起见,您可以通过以下方式执行while循环:
int index = 0;
while(index < myArray.length)
{
final String value;
value = myArray[index];
System.out.println(value);
index++;
}
Run Code Online (Sandbox Code Playgroud)
但是当你知道大小时你应该使用for循环而不是while循环(甚至使用可变长度数组你知道它的大小......每次都是不同的).
数组有一个包含长度的隐式成员变量:
for(int i=0; i<myArray.length; i++) {
System.out.println(myArray[i]);
}
Run Code Online (Sandbox Code Playgroud)
或者,如果使用> = java5,则为每个循环使用a:
for(Object o : myArray) {
System.out.println(o);
}
Run Code Online (Sandbox Code Playgroud)