Java 增強型的for循環 for each


 

For-Each循環

  For-Each循環也叫增強型的for循環,或者叫foreach循環。

  For-Each循環是JDK5.0的新特性(其他新特性比如泛型、自動裝箱等)。

  For-Each循環的加入簡化了集合的遍歷。

 

其語法如下:

  for(type element: array)

  {

        System.out.println(element);

  }

 

例子

  其基本使用可以直接看代碼:

  代碼中首先對比了兩種for循環;之后實現了用增強for循環遍歷二維數組;最后采用三種方式遍歷了一個List集合。

  

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ForeachTest
{
    public static void main(String[] args)
    {
        int[] arr = {1, 2, 3, 4, 5};
        
        System.out.println("----------舊方式遍歷------------");
        //舊式方式        
        for(int i=0; i<arr.length; i++)
        {
            System.out.println(arr[i]);
        }
        
        System.out.println("---------新方式遍歷-------------");
        
        //新式寫法,增強的for循環
        for(int element:arr)
        {
            System.out.println(element);
        }
        
        System.out.println("---------遍歷二維數組-------------");
        
        //遍歷二維數組
        
        int[][] arr2 = {{1, 2, 3}, {4, 5, 6}, {7, 8, 9}} ;
        
        for(int[] row : arr2)
        {
            for(int element : row)
            {
                System.out.println(element);
            }
        }
        
        //以三種方式遍歷集合List
        
        List<String> list = new ArrayList<String>();
        
        list.add("a");
        list.add("b");
        list.add("c");
        
        System.out.println("----------方式1-----------");
        //第一種方式,普通for循環
        for(int i = 0; i < list.size(); i++)
        {
            System.out.println(list.get(i));
            
        }
        
        System.out.println("----------方式2-----------");
        //第二種方式,使用迭代器
        for(Iterator<String> iter = list.iterator(); iter.hasNext();)
        {
            System.out.println(iter.next());
        }
        System.out.println("----------方式3-----------");
        //第三種方式,使用增強型的for循環
        for(String str: list)
        {
            System.out.println(str);
            
        }
    }

}

 

  For-Each循環的缺點:丟掉了索引信息。

  當遍歷集合或數組時,如果需要訪問集合或數組的下標,那么最好使用舊式的方式來實現循環或遍歷,而不要使用增強的for循環,因為它丟失了下標信息。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM