java For Each 迴圈語句的使用方法

來源:互聯網
上載者:User

 for each是jdk5.0新增加的一個迴圈結構,可以用來以此處理數組中的每個元素(其他類型的元素集合也可以)而不用為指定下標而分心。

格式如下

for(type itr-var : iterableObj) statement-block

    定義一個變數用於暫存集合中的每一個元素,並執行相應的語句(當然,也可以是語句塊)。集合運算式必須是一個數組或者是一個實現了lterable介面的類(例如ArrayList)對象。

例如:

public class ClsTest {
    public static void main(String[] args) {
            int[] a=new int[10];
            for(int b:a){
            System.out.println(b);
  }  }  }


對於集合類型和數群組類型的,我們都可以通過foreach文法來訪問它。上面的例子中,以前我們要依次訪問數組,挺麻煩:

public class MainClass {
  public static void main(String args[]) {
    int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
 
    for(int x : nums) {
      System.out.print(x + " ");
      x = x * 10; // no effect on nums
    }
  
    System.out.println();

    for(int x : nums)
      System.out.print(x + " ");

    System.out.println();
  } 
}


 
現在只需下面簡單的語句即可:

for (type identifier : iterable_expression) {
  // statements
}
 
public class MainClass {
  enum Season {
    spring, summer, fall, winter
  }

  public static void main(String[] args) {
    for (Season season : Season.values()) {
      System.out.println(" The season is now " + season);
    }
  }
}


 

對集合的訪問效果更明顯。以前我們訪問集合的代碼:

import java.util.ArrayList;
 
public class MainClass {
   
  public static void main(String args[]) {
    ArrayList<Double> list = new ArrayList<Double>();

    list.add(10.14);
    list.add(20.22);
    list.add(30.78);
    list.add(40.46);

    double sum = 0.0;
    for(double itr : list)
      sum = sum + itr;
    System.out.println(sum);
 
  }
}

另一種方法

public class MainClass {
  public static void main(String args[]) {
    int nums[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    int sum = 0;

    // use for-each style for to display and sum the values
    for(int x : nums) {
      System.out.println("Value is: " + x);
      sum += x;
    }

    System.out.println("Summation: " + sum);
  }
}
 
Value is: 1
Value is: 2
Value is: 3
Value is: 4
Value is: 5
Value is: 6
Value is: 7
Value is: 8
Value is: 9
Value is: 10
Summation: 55
 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.