語法
示例
import java.util.Collection;
public class Foreach
{
private Collection c = null;
private String[] belle = new String[4];
public Foreach()
{
belle[0] = "西施";
belle[1] = "王昭君";
belle[2] = "貂禪";
belle[3] = "楊貴妃";
c = Arrays.asList(belle);
}
public void testCollection()
{
for (String b : c)
{
System.out.println("曾經的風化絕代:" + b);
}
}
public void testArray()
{
for (String b : belle)
{
System.out.println("曾經的青史留名:" + b);
}
}
public static void main(String[] args)
{
Foreach each = new Foreach();
each.testCollection();
each.testArray();
}
}
在以前的代碼中,我們可以通過Iterator執行remove操作。
但是,在現在的foreach版中,我們無法刪除集合包含的對象。你也不能替換對象。
同時,你也不能并行的foreach多個集合。所以,在我們編寫代碼時,還得看情況而使用它。
新聞熱點
疑難解答