遍历可变长度数组 [英] Iterating through a variable length array
问题描述
如何遍历可变长度的 Java 数组.
How do I iterate over a Java array of variable length.
我想我会设置一个 while 循环,但是我如何检测到我已经到达数组的末尾.
I guess I would setup a while loop, but how would I detect that I have reached the end of the array.
我想我想要这样的东西[只需要弄清楚如何表示 myArray.notEndofArray()]
I guess I want something like this [just need to figure out how to represent myArray.notEndofArray()]
index = 0;
while(myArray.notEndofArray()){
system.out.println(myArray(index));
index++;
}
推荐答案
for(int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}
或
for(String value : array)
{
System.out.println(value);
}
第二个版本是for-each"循环,它适用于数组和集合.大多数循环都可以使用 for-each 循环来完成,因为您可能并不关心实际的索引.如果您确实关心实际索引,请使用第一个版本.
The second version is a "for-each" loop and it works with arrays and Collections. Most loops can be done with the for-each loop because you probably don't care about the actual index. If you do care about the actual index us the first version.
为了完整起见,您可以这样执行 while 循环:
Just for completeness you can do the while loop this way:
int index = 0;
while(index < myArray.length)
{
final String value;
value = myArray[index];
System.out.println(value);
index++;
}
但是当您知道大小时,您应该使用 for 循环而不是 while 循环(即使使用可变长度数组,您也知道大小......每次都不同).
But you should use a for loop instead of a while loop when you know the size (and even with a variable length array you know the size... it is just different each time).
这篇关于遍历可变长度数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!