java5特性:增强FOR循环

遍历数组
语法:
--------new---------
for(Type value:array) {
    expression value;
}
--------old---------
for(int i = 0;i < array.length; i++){
int n = arrar[i];
do something;
}

遍历集合
注意:for-each循环遍历的集合必须是实现Iterable接口
语法:
--------new---------
for (Type value:Iterable) ...{
    expression value;
}
--------old---------
for(Iterator iter = list.iterator(); iter.HasNext();){
Object o = iter.next();
do something;
}

例子:
遍历数组
求一个数组中所有的值的和.
----------------old-----------------
void testArrayOld(){
   int[] arrayOld = {1,2,3,4};
   int totalOld = 0;
   for(int i = 0;i < arrayOld.length;i++){
       totalOld += arrayOld[i];
   }   
   System.out.println(totalOld);
}

----------------new-----------------
void testArrauNew(){
    int[] array = {1,2,3,4};
    int totalNew = 0;
    int i = 0;
    for(int n:array){
    //循环变量(i)不可见;n为循环变量
    totalNew += n;
    }
    System.out.println(totalNew);
}


遍历集合
拼接list中的所有字符。
----------------old-----------------
void testListOld(){
    List listOld = new ArrayList();
    listOld.add("Agile");
    listOld.add(" ");
    listOld.add("Java");
    String strOld = "";
    for(Iterator iter = listOld.iterator();iter.hasNext();){
    String strTemp = (String)iter.next();
    strOld += strTemp;
    }
    System.out.println(strOld);
}

----------------new-----------------
void testListNew(){
     List<String> listNew = new ArrayList<String>();
     listNew.add("Agile");
     listNew.add(" ");
     listNew.add("Java");
    String str = "";
    for(String strTemp:listNew){
     str += strTemp;
    }
    System.out.println(str);
}


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


public class TestFor {
	public static void main(String[] args) {
		//old 数组		
		int[] arrayOld = {1,2,3,4};
	    int totalOld = 0;
	    for(int i = 0;i < arrayOld.length;i++){
	    	totalOld += arrayOld[i];
	    }    
	    System.out.println(totalOld);

	    //new数组		
	    int[] array = {1,2,3,4};
	    int totalNew = 0;
	    int i = 0;
	    for(int n:array){
	    	//循环变量(i)不可见;n为循环变量
	    	totalNew += n;
	    }
	    System.out.println(totalNew);
		
	    //old list
		List listOld = new ArrayList();
		listOld.add("Agile");
		listOld.add(" ");
		listOld.add("Java");
	    String strOld = "";
	    for(Iterator iter = listOld.iterator();iter.hasNext();){
	    	String strTemp = (String)iter.next();
	    	strOld += strTemp; 
	    }
	    System.out.println(strOld);
		
	    //new list
		List<String> listNew = new ArrayList<String>();
		listNew.add("Agile");
		listNew.add(" ");
		listNew.add("Java");
	    String str = "";
	    for(String strTemp:listNew){
	     	str += strTemp; 
	    }
	    System.out.println(str);
	}	
}

你可能感兴趣的:(java)