How does the Java 'for each' loop work?

2018-12-30 23:26发布

Consider:

List<String> someList = new ArrayList<String>();
// add "monkey", "donkey", "skeleton key" to someList
for (String item : someList) {
    System.out.println(item);
}

What would the equivalent for loop look like without using the for each syntax?

26条回答
美炸的是我
2楼-- · 2018-12-30 23:56

It would look something like this. Very crufty.

for (Iterator<String> i = someList.iterator(); i.hasNext(); )
        System.out.println(i.next());

There is a good writeup on for each in the Sun documentation.

查看更多
闭嘴吧你
3楼-- · 2018-12-30 23:57

As defined in JLS for-each loop can have two forms:

  1. If the type of Expression is a subtype of Iterable then translation is as:

    List<String> someList = new ArrayList<String>();
    someList.add("Apple");
    someList.add("Ball");
    for (String item : someList) {
        System.out.println(item);
    }
    
    // IS TRANSLATED TO:
    
    for(Iterator<String> stringIterator = someList.iterator(); stringIterator.hasNext(); ) {
        String item = stringIterator.next();
        System.out.println(item);
    }
    
  2. If the Expression necessarily has an array type T[] then:

    String[] someArray = new String[2];
    someArray[0] = "Apple";
    someArray[1] = "Ball";
    
    for(String item2 : someArray) {
        System.out.println(item2);
    }
    
    // IS TRANSLATED TO:
    for (int i = 0; i < someArray.length; i++) {
        String item2 = someArray[i];
        System.out.println(item2);
    }
    

Java 8 has introduced streams which perform generally better. We can use them as:

someList.stream().forEach(System.out::println);
Arrays.stream(someArray).forEach(System.out::println);
查看更多
春风洒进眼中
4楼-- · 2018-12-30 23:58

It's implied by nsayer's answer, but it's worth noting that the OP's for(..) syntax will work when "someList" is anything that implements java.lang.Iterable -- it doesn't have to be a list, or some collection from java.util. Even your own types, therefore, can be used with this syntax.

查看更多
几人难应
5楼-- · 2018-12-30 23:58
List<Item> Items = obj.getItems();
for(Item item:Items)
             {
                System.out.println(item); 
             }

Iterates over all the objects in Items table.

查看更多
初与友歌
6楼-- · 2018-12-30 23:59

This looks crazy but hey it works

List<String> someList = new ArrayList<>(); //has content
someList.forEach(System.out::println);

This works. Magic

查看更多
泪湿衣
7楼-- · 2018-12-31 00:01

In Java 8 features you can use this:

List<String> messages = Arrays.asList("First", "Second", "Third");

void forTest(){
    messages.forEach(System.out::println);
}

Output

First
Second
Third
查看更多
登录 后发表回答