Quantcast
Viewing all articles
Browse latest Browse all 30

Answer by L Joey for In detail, how does the 'for each' loop work in Java?

As so many good answers said, an object must implement the Iterable interface if it wants to use a for-each loop.

I'll post a simple example and try to explain in a different way how a for-each loop works.

The for-each loop example:

public class ForEachTest {    public static void main(String[] args) {        List<String> list = new ArrayList<String>();        list.add("111");        list.add("222");        for (String str : list) {            System.out.println(str);        }    }}

Then, if we use javap to decompile this class, we will get this bytecode sample:

public static void main(java.lang.String[]);    flags: ACC_PUBLIC, ACC_STATIC    Code:      stack=2, locals=4, args_size=1         0: new           #16                 // class java/util/ArrayList         3: dup         4: invokespecial #18                 // Method java/util/ArrayList."<init>":()V         7: astore_1         8: aload_1         9: ldc           #19                 // String 111        11: invokeinterface #21,  2           // InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z        16: pop        17: aload_1        18: ldc           #27                 // String 222        20: invokeinterface #21,  2           // InterfaceMethod java/util/List.add:(Ljava/lang/Object;)Z        25: pop        26: aload_1        27: invokeinterface #29,  1           // InterfaceMethod java/util/List.iterator:()Ljava/util/Iterator;

As we can see from the last line of the sample, the compiler will automatically convert the use of for-each keyword to the use of an Iterator at compile time. That may explain why object, which doesn't implement the Iterable interface, will throw an Exception when it tries to use the for-each loop.


Viewing all articles
Browse latest Browse all 30

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>