영어로 읽는 코딩

26_[자바] foreach

Foreach syntax

Java SE5 introduces a new and more succinct for syntax, for use with arrays and containers. This is often called the foreach syntax, and it means that you don’t have to create an int to count through a sequence of items—the foreach produces each item for you, automatically.

For example, suppose you have an array of float and you’d like to select each element in that array:

//: control/ForEachFloat.java
import java.util.*;
public class ForEachFloat {
  public static void main(String[] args) {
    Random rand = new Random(47);
    float f[] = new float[10];
    for(int i = 0; i < 10; i++)
      f[i] = rand.nextFloat();
    for(float x : f)
      System.out.println(x);
  }
} /* Output:
0.72711575
0.39982635
0.5309454
0.0534122
0.16020656
0.57799757
0.18847865
0.4170137
0.51660204
0.73734957
*///:~

 

The array is populated using the old for loop, because it must be accessed with an index. You can see the foreach syntax in the line:

for(float x : f) {

This defines a variable x of type float and sequentially assigns each element of f to x.

Any method that returns an array is a candidate for use with foreach. For example, the String class has a method toCharArray( ) that returns an array of char, so you can easily iterate through the characters in a string:

//: control/ForEachString.java
public class ForEachString {
  public static void main(String[] args) {
    for(char c : "An African Swallow".toCharArray() )
      System.out.print(c + " ");
  }
} /* Output:
A n   A f r i c a n   S w a l l o w
*///:~

 

As you’ll see in the Holding Your Objects chapter, foreach will also work with any object that is Iterable.

 

 

[Thinking in Java 97]

댓글

댓글 본문
버전 관리
Yoo Moon Il
현재 버전
선택 버전
graphittie 자세히 보기