foreach語(yǔ)法相信大家都不會(huì)陌生吧,接下來我們進(jìn)行詳細(xì)分析,提出幾個(gè)問題?
先看代碼:
public class T01 implements Iterable<Integer>{ @Override public Iterator<Integer> iterator() { return new Iterator<Integer>() { @Override public boolean hasNext() { return true; } @Override public Integer next() { return 1; } @Override public void remove() { } }; } public static void main(String[] args) { T01 t01 = new T01(); for (Integer integer : t01) { System.out.PRintln(integer); } }}當(dāng)然程序會(huì)無限打印,為了演示我并沒有優(yōu)化。看出來了吧,要使用foreach語(yǔ)法,必須實(shí)現(xiàn)接口Iterable;
看代碼:
public class T01{ public static void main(String[] args) { List<Integer> list = new ArrayList<Integer>(); for (Integer each : list) { } }}我們進(jìn)行javap編譯:
public static void main(java.lang.String[]); Code: 0: new #16 // class java/util/ArrayList 3: dup 4: invokespecial #18 // Method java/util/ArrayList."<init>":()V 7: astore_1 8: aload_1 //ArrayList實(shí)例入棧 9: invokeinterface #19, 1 // InterfaceMethod java/util/List.iterator:()Ljava/util/Iterator; 14: astore_3 //構(gòu)造遍歷器,并保存到局部變量 3中, 15: goto 28 //一下都是遍歷跳轉(zhuǎn)到28 18: aload_3 19: invokeinterface #25, 1 // InterfaceMethod java/util/Iterator.next:()Ljava/lang/Object; 24: checkcast #31 // class java/lang/Integer 27: astore_2 28: aload_3 29: invokeinterface #33, 1 // InterfaceMethod java/util/Iterator.hasNext:()Z 34: ifne 18 //棧頂數(shù)不為0跳轉(zhuǎn)到18,也就是next方法。為什么不是判斷true。因?yàn)樘摂M機(jī)考慮到指令太多會(huì)造成沒必要的復(fù)雜度,對(duì)boolean只提供有限的支持,在Java中涉及到boolean類型值的運(yùn)算,在編譯之后都使用int數(shù)據(jù)類型來代替。 37: return看到這里應(yīng)該明白了吧,其實(shí)就是對(duì)foreach語(yǔ)法編譯期優(yōu)化,運(yùn)用Iterator進(jìn)行遍歷。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注