Thinking in java(一)--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.
一、Example, suppose you have an array of float and you`d like to select each element in that array:
1 package ForeachSyntax; 2 import java.util.Random; 3 public class ForEachFloat { 4 public static void main(String[] args) { 5 Random rand = new Random(47); 6 float f[] = new float[10]; 7 for(int i = 0; i <10; i++){ 8 f[i] = rand.nextFloat(); 9 } 10 /* foreach syntax */ 11 for(float x : f){ 12 System.out.println(x); 13 } 14 } 15 }
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, becase 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;
二、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:
1 package ForeachSyntax; 2 public class ForEachString { 3 public static void main(String[] args) { 4 String s = "hello world"; 5 for(char c : s.toCharArray()){ 6 System.out.print(c); 7 } 8 } 9 }
Output:
hello world
Foreach will also work with any object that is Iterable.
作者:CodingBlock
出处:http://www.cnblogs.com/codingblock/
本文版权归作者和共博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
如果文中有什么错误,欢迎指出。以免更多的人被误导。