![](/img/trans.png)
[英]Is there a Ruby version of for-loop similar to the one on Java/C++?
[英]Is there FOR … IN … loop in Java similar to Python one?
我可以使用Python循環遍歷數組
arr = []
for e in arr:
do smth. with each element
Java是否有類似的循環? 如果我要像這樣在Java中拆分字符串:
temp = str.split(delimiter);
我是否可以使用“ for ... in ...”類似的語句循環使用數組?
有foreach
“聲明”:
for (final E element: array) {
// do whatever with element
}
它也適用於數組和各種Collections(集合,列表,地圖),並且通常適用於實現Iterable<X>
任何X
類,即本身具有Iterable
的類(這意味着您可以編寫一個類用於foreach語句,這很好)。
因此,您可以直接寫:
for (final String s: str.split(delimiter)) {
// work with s
}
因為.split()
返回一個數組,該數組可直接與foreach語句一起使用。 也就是說,無論出於何種原因,如果您不需要其他變量來保存數組索引。
for (String part: str.split(delimiter)){
// ....
}
for循環存在於java中。
http://www.roseindia.net/java/beginners/ForLoop.shtml
在Java 1.5中,使用增強的for循環。
for (String str : temp) {
System.out.println(str);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.