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:49

A foreach loop syntax is:

for (type obj:array) {...}

Example:

String[] s = {"Java", "Coffe", "Is", "Cool"};
for (String str:s /*s is the array*/) {
    System.out.println(str);
}

Output:

Java
Coffe
Is
Cool

WARNING: You can access array elements with the foreach loop, but you can NOT initialize them. Use the original for loop for that.

WARNING: You must match the type of the array with the other object.

for (double b:s) // Invalid-double is not String

If you want to edit elements, use the original for loop like this:

for (int i = 0; i < s.length-1 /*-1 because of the 0 index */; i++) {
    if (i==1) //1 because once again I say the 0 index
        s[i]="2 is cool";
    else
        s[i] = "hello";
}

Now if we dump s to the console, we get:

hello
2 is cool
hello
hello
查看更多
骚的不知所云
3楼-- · 2018-12-30 23:49

The Java for each loop (aka enhanced for loop) is a simplified version of a for loop. The advantage is that there is less code to write and less variables to manage. The downside is that you have no control over the step value and no access to the loop index inside the loop body.

They are best used when the step value is a simple increment of 1 and when you only need access to the current loop element. For example, if you need to loop over every element in an array or Collection without peeking ahead or behind the current element.

There is no loop initialization, no boolean condition and the step value is implicit and is a simple increment. This is why they are considered so much simpler than regular for loops.

Enhanced for loops follow this order of execution:

1) loop body

2) repeat from step 1 until entire array or collection has been traversed

Example – Integer Array

int [] intArray = {1, 3, 5, 7, 9};
for(int currentValue : intArray) {
  System.out.println(currentValue);
}

The currentValue variable holds the current value being looped over in the intArray array. Notice there’s no explicit step value – it’s always an increment by 1.

The colon can be thought of to mean “in”. So the enhanced for loop declaration states: loop over intArray and store the current array int value in the currentValue variable.

Output:

1
3
5
7
9

Example – String Array

We can use the for-each loop to iterate over an array of strings. The loop declaration states: loop over myStrings String array and store the current String value in the currentString variable.

String [] myStrings  = {
  "alpha",
  "beta",
  "gamma",
  "delta"
};

for(String currentString : myStrings) {
  System.out.println(currentString);
}

Output:

alpha
beta
gamma
delta

Example – List

The enhanced for loop can also be used to iterate over a java.util.List as follows:

List<String> myList = new ArrayList<String>();
myList.add("alpha");
myList.add("beta");
myList.add("gamma");
myList.add("delta");

for(String currentItem : myList) {
  System.out.println(currentItem);
}

The loop declaration states: loop over myList List of Strings and store the current List value in the currentItem variable.

Output:

alpha
beta
gamma
delta

Example – Set

The enhanced for loop can also be used to iterate over a java.util.Set as follows:

Set<String> mySet = new HashSet<String>();
mySet.add("alpha");
mySet.add("alpha");
mySet.add("beta");
mySet.add("gamma");
mySet.add("gamma");
mySet.add("delta");

for(String currentItem : mySet) {
  System.out.println(currentItem);
}

The loop declaration states: loop over mySet Set of Strings and store the current Set value in the currentItem variable. Notice that since this is a Set, duplicate String values are not stored.

Output:

alpha
delta
beta
gamma

Source: Loops in Java – Ultimate Guide

查看更多
无与为乐者.
4楼-- · 2018-12-30 23:51
for (Iterator<String> itr = someList.iterator(); itr.hasNext(); ) {
   String item = itr.next();
   System.out.println(item);
}
查看更多
后来的你喜欢了谁
5楼-- · 2018-12-30 23:51

The Java for-each idiom can only be applied to arrays or objects of type *Iterable. This idiom is implicit as it truly backed by an Iterator. The Iterator is programmed by the programmer and often uses an integer index or a node (depending on the data structure) to keep track of its position. On paper it is slower than a regular for-loop, a least for "linear" structures like arrays and Lists but it provides greater abstraction.

查看更多
旧时光的记忆
6楼-- · 2018-12-30 23:55

Using older Java versions including Java 7 you can use foreach loop as follows.

List<String> items = new ArrayList<>();
        items.add("A");
        items.add("B");
        items.add("C");
        items.add("D");
        items.add("E");

        for(String item : items){
            System.out.println(item);
        }

Following is the very latest way of using foreach loop in Java 8

(loop a List with forEach + lambda expression or method reference)

//lambda
    //Output : A,B,C,D,E
    items.forEach(item->System.out.println(item));


//method reference
    //Output : A,B,C,D,E
    items.forEach(System.out::println);

For more info refer this link.

https://www.mkyong.com/java8/java-8-foreach-examples/

查看更多
心情的温度
7楼-- · 2018-12-30 23:55

It adds beauty to your code by removing all the basic looping clutter. It gives a clean look to your code, justified below.

Normal for loop:

void cancelAll(Collection<TimerTask> list) {
    for (Iterator<TimerTask> i = list.iterator(); i.hasNext();)
         i.next().cancel();
}

Using for-each:

void cancelAll(Collection<TimerTask> list) {
    for (TimerTask t : list)
        t.cancel();
}

for-each is a construct over a collection that implements Iterator. Remember that, your collection should implement Iterator; otherwise you can't use it with for-each.

The following line is read as "for each TimerTask t in list."

for (TimerTask t : list)

There is less chance for errors in case of for-each. You don't have to worry about initializing the iterator or initializing the loop counter and terminating it (where there is scope for errors).

查看更多
登录 后发表回答