簡體   English   中英

Java 中增強的 for 循環的語法是什么?

[英]What is the syntax of the enhanced for loop in Java?

我被要求在我的編碼中使用增強的for循環。

我只學過如何使用傳統的for循環,因此不知道它與增強的for循環之間的區別。

增強的for循環與 Java 中的傳統for循環有何不同?

我應該注意哪些教程傾向於不提及的任何錯綜復雜的地方?

增強的 for 循環:

for (String element : array) {

    // rest of code handling current element
}

傳統的 for 循環等效:

for (int i=0; i < array.length; i++) {
    String element = array[i]; 

    // rest of code handling current element
}

看看這些論壇: https : //blogs.oracle.com/CoreJavaTechTips/entry/using_enhanced_for_loops_with

http://www.java-tips.org/java-se-tips/java.lang/the-enhanced-for-loop.html

增強的for循環只是限制括號內的參數數量。

for (int i = 0; i < myArray.length; i++) {
    System.out.println(myArray[i]);
}

可以寫成:

for (int myValue : myArray) {
    System.out.println(myValue);
}
  1. 增強的 For 循環 (Java)
for (Object obj : list);
  1. 增強數組列表中的每個(Java)
ArrayList<Integer> list = new ArrayList<Integer>(); 
list.forEach((n) -> System.out.println(n)); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM