/*
* foreach:增強for循環,一般用於遍歷集合或者數組
* 格式:
* for(元素的類型 變量 : 集合或者數組對象) {
* 可以直接使用變量;
* }
注意:在增強for循環中不能修改集合,否則會出現並發修改異常。
public interface Iterable<T>
實現這個接口允許對象成為 "foreach" 語句的目標。
*/
public class ForEachDemo { public static void main(String[] args) { Collection<String> c = new ArrayList<String>(); c.add("hello"); c.add("world"); /*for(Object obj : c) { System.out.println(obj); }*/ for(String s : c) { // c.add("android"); // foreach使用的迭代器實現,所以不能在變量時更改 System.out.println(s); } } }
輸出

