今天接觸了一個以前看到過但完全朦朧的東西->那就是foreach循環,網上查閱后得到語法如下
for(元素類型 元素名稱 : 遍歷數組(集合)(或者能進行迭代的)){
語句
}
由於for括號內沒有邏輯表達式,所以它適用於循環次數不知道的情況下會使得代碼更加簡便(暫時這么理解,具體與for循環之間的效率的區別未知)
這個增強的for循環,對map類的鍵值對,也可以使用,例子如下:
1 public class Test{ 2 public static void main(String[] args) { 3 Map<String,Integer> testmap = new LinkedHashMap<String, Integer>(); 4 //這里的Integer不能替換為int(似乎這里的類型定義不能使用基本類型,只能使用基本類型的包裝類) 5 testmap.put("s1",1); 6 testmap.put("s2",2); 7 testmap.put("s3",3); 8 //Map.Entry<String,Integer>可以算是一個類型,表明這個鍵值對集合里鍵值對的類型 9 for(Map.Entry<String,Integer> s : testmap.entrySet()){ 10 System.out.println("'" + s.getKey() + "':" + s.getValue()); 11 } 12 } 13 }
在使用foreach時,不能對數組(集合)做添加刪除,因為使用foreach時數組(集合)已被鎖定不能修改,否則會報出java.util.ConcurrentModificationException異常