迭代可变长度数组
如何迭代可变长度的 Java 数组。
我想我会设置一个 while 循环,但是我如何检测到我已经到达数组的末尾。
我想我想要这样的东西[只需要弄清楚如何表示 myArray.notEndofArray()]
index = 0;
while(myArray.notEndofArray()){
system.out.println(myArray(index));
index++;
}
How do I iterate over a Java array of variable length.
I guess I would setup a while loop, but how would I detect that I have reached the end of the array.
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++;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
或
第二个版本是“for-each”循环,它适用于数组和集合。大多数循环可以使用 for-each 循环完成,因为您可能不关心实际索引。如果您确实关心实际索引,请使用第一个版本。
为了完整起见,您可以这样执行 while 循环:
但是当您知道大小时,您应该使用 for 循环而不是 while 循环(即使使用可变长度数组,您也知道大小......每次都不同)。
or
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.
Just for completeness you can do the while loop this way:
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).
数组有一个隐式成员变量来保存长度:
或者,如果使用 >=java5,则对每个循环使用一个:
Arrays have an implicit member variable holding the length:
Alternatively if using >=java5, use a for each loop:
您在问题中特别提到了“可变长度数组”,因此现有的两个答案(正如我写的那样)都不完全正确。
Java 没有任何“可变长度数组”的概念,但它有 Collections,可以起到这种作用。任何集合(技术上任何“Iterable”,集合的超类型)都可以像这样简单地循环:
编辑:我可能误解了他所说的“可变长度”的含义。他可能只是意味着它是固定长度,但并非每个实例都是相同的固定长度。在这种情况下,现有的答案就可以了。我不确定这是什么意思。
You've specifically mentioned a "variable-length array" in your question, so neither of the existing two answers (as I write this) are quite right.
Java doesn't have any concept of a "variable-length array", but it does have Collections, which serve in this capacity. Any collection (technically any "Iterable", a supertype of Collections) can be looped over as simply as this:
EDIT: it's possible I misunderstood what he meant by 'variable-length'. He might have just meant it's a fixed length but not every instance is the same fixed length. In which case the existing answers would be fine. I'm not sure what was meant.
这是一个示例,其中数组的长度在循环执行期间发生变化
here is an example, where the length of the array is changed during execution of the loop