采摘处:http://java.e800.com.cn/articles/2008/84/1217828900220_1.html
package com.test.For_Each;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ForTest
{
public static void main(String args[])
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
/**
* 新式写法
*/
for (int a : arr)
System.out.println(a);
/**
* 旧式写法
*/
for (int i = 0; i < arr.length; i++)
System.out.println(arr[i]);
String arr2[] = {"好","流","哦","!!"};
for(String a2 : arr2)
System.out.println(a2);
int arr3[][] = {{1,2,3},{4,5,6,},{7,8,9}};
for(int a31[] : arr3)
{
for(int a32 : a31)
{
System.out.println(a32);
}
System.out.println();
}
List<String> list = new ArrayList<String>();
list.add("好");
list.add("流");
list.add("哦");
list.add("!!");
/**
* 根据集合类长度遍历
*/
for(int i=0;i<list.size();i++)
{
System.out.println(list.get(i));
}
/**
* 根据迭代器遍历
*/
for(Iterator i = list.iterator();i.hasNext();)
{
System.out.println(i.next());
}
/**
* 根据新式for-each遍历
*/
for(String element : list)
System.out.println(element);
}
}