迭代可变长度数组 [英] 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屋!