for(init; condition; update)for(Type item : collection)對比四組方法的編譯位元碼:
superForeachTestArray:陣列增強 forforeachTestArray:陣列傳統 for(手寫等效邏輯)superForeachTestIterator:List 增強 forforeachTestIterator:Iterator 手寫遍歷使用 javap -v 反編譯 ForeachTest.class:
arraylength、aaload)Iterable 介面:編譯器轉換為 iterator() → hasNext()/next() 迴圈aload_1 // 載入陣列參考
arraylength // 取得長度
istore_2 // 存入區域變數
iconst_0 // i = 0
istore_3
iload_3 // 載入 i
iload_2 // 載入 length
if_icmpge 46 // i >= length 跳出
aload_1 // 載入陣列
iload_3 // 載入 i
aaload // 取得元素
astore 4 // 存入區域變數 s
... // 呼叫 println
iinc 3, 1 // i++
goto 22 // 回頭判斷
aload_0 // 載入 List
invokeinterface iterator() // 取得 Iterator
astore_1
aload_1
invokeinterface hasNext() // 檢查是否有下一個
ifeq 54 // 無則跳出
aload_1
invokeinterface next() // 取得下一個
checkcast String // 型別檢查
astore_2
... // 呼叫 println
goto 25 // 回頭判斷
ConcurrentModificationException