码迷,mamicode.com
首页 > 编程语言 > 详细

Java中的Foreach使用

时间:2015-03-16 16:12:44      阅读:131      评论:0      收藏:0      [点我收藏+]

标签:

Foreach 是JAVA SE5 引入的一种新的更加简洁的语法,在遍历数组和容器方面带来极大的便利,但是也有其局限性。

 

foreach的语句格式:

for(元素类型t 元素变量x : 遍历对象obj){

     引用了x的java语句;

}

foreach简化数组的遍历

示例一(一维数组):

 1 import java.util.Random;
 2 public class Foreach {
 3     public static void main(String[] args) {
 4         Random rand = new Random();
 5         int[] t = new int[5];
 6         //初始化数组
 7         for(int i=0;i<t.length;i++)
 8             t[i] = rand.nextInt(100);
 9         
10         //使用foreach遍历数组
11         for(int x:t)
12             System.out.print(x + "  ");
13     }
14 }
15 /*
16  *输出结果:
17  *3  46  12  27  95 
18  *
19  */ 

 

示例二(二维数组)

 1 public class Foreach {
 2     public static void main(String[] args) {
 3         //初始化数组
 4         int[][] t = {
 5                 {2,3,4,5},
 6                 {1,6,7,8}
 7         };
 8         
 9         //使用foreach遍历数组
10         for(int x[]:t){
11             for(int m : x)
12                 System.out.print(m + "  ");
13             System.out.println();
14         }
15     }
16 }
17 /*
18  * 输出结果:
19  * 2  3  4  5  
20  * 1  6  7  8
21  * 
22  */

但是,值得注意的是,foreach是无法完成赋值的,也就是说,数组对于foreach语句而言只是“只读”的。

示例三(foreach无法完成赋值)

 1 import java.util.Random;
 2 public class Foreach {
 3     public static void main(String[] args) {
 4         Random rand = new Random();
 5         int[] t = new int[5];
 6         //初始化数组
 7         for(int i=0;i<t.length;i++)
 8             t[i] = rand.nextInt(100);
 9         
10         //使用foreach遍历数组
11         for(int x:t)
12             System.out.print(x + "  ");
13         System.out.println();
14         
15         //使用foreach进行赋值(注意,这是错误的做法)
16         for(int x:t)
17             x = rand.nextInt(100);
18         //再次遍历数组
19         for(int x:t)
20             System.out.print(x + "  ");
21     }
22 }
23 /*
24  * 输出结果:
25  * 41  83  77  44  80
26  * 41  83  77  44  80
27  * 
28  */

从上面示例三可以看出来,foreach是无法对数组进行赋值的,foreach是按以下方式执行的

1 for( T x : obj){
2     x = obj[i];
3     x = 随机数;
4     
5 }

所以才会导致无法对数组进行赋值。

Java中的Foreach使用

标签:

原文地址:http://www.cnblogs.com/ypli/p/4341862.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!