java中foreach的使用

java中foreach的使用

 

Java5之后新增了foreach语法,可以看成for循环的一个扩展,其主要用处在于使得遍历数组或者其他集合(collections)更为方便。这个新语法命名为enhanced for或者foreeach(参考其他语言的命名方式)。

foreach可用于遍历数组和Collections中每一个连续的值。当然它也可以用于遍历那些已经实现了Iterable<E> 的接口的对象(需要定义iterator()函数),而许多Collections类都已经实现了Iterable<E>,这使得 foreach语法用了用武之地。

通用格式

以下列出foreach和for的使用形式,同时给出两个基本的对等式,区别在于是数组还是其他可迭代对象。

例子-计算数组中各元素和

foreach语法实现:

?
1
2
3
4
5
double [] ar = { 1.2 , 3.0 , 0.8 };
int sum = 0 ;
for ( double d : ar) {  // d gets successively each value in ar.
     sum += d;
}

for语法的实现:

?
1
2
3
4
5
double [] ar = { 1.2 , 3.0 , 0.8 };
int sum = 0 ;
for ( int i = 0 ; i < ar.length; i++) {  // i indexes each element successively.
     sum += ar[i];
}

何时使用foreach合适

从上方例子中可以看出,foreach有些时候能够使得代码变得干净,但是需要注意某些情况写不合适:

  1. 只读:访问的元素不能被赋值,比如元素的自增等
  2. 单一结构:不可能同时遍历两个结构,比如比较两个数组
  3. 单一元素:只适合单一的元素读取
  4. 单向:只能向前单个元素的迭代
  5. 需java5支持:不要在java5前使用该语法

二维数组中foreach的使用

举例:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class test02 {
     public static void main(String args[])
     {
         int [][] a = new int [][] {
             { 1 , 2 , 3 , 4 , 5 },
             { 10 , 11 , 12 }
         };
 
         for ( int [] row : a) {
             for ( int element : row)
                 System.out.print(element + " " );
             System.out.println();
         }
     }
}

foreach更多运用

前面已经说了foreach适用于遍历数组或者Collections等实现了Iterable<T>接口的对象。例如遍历List或者Set:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
//List
public void go(List<String> list) {
     for (String element : list) {
         System.out.println(element);
     }
}
 
//set
public void go(Set<String> set) {
     for (String element : set) {
         System.out.println(element);
     }
}

Collections的遍历如下:

?
1
2
3
4
5
public void go(Collection<String> collection) {
     for (String element : collection) {
         System.out.println(element);
     }
}

其实在编译的时候,编译器会把foreach展开,比如上面的Collections展开如下:

?
1
2
3
4
5
6
public void go(Collection collection) {
     String s;
     for (Iterator iterator = collection.iterator();
         iterator.hasNext(); System.out.println(s))
         s = (String)iterator.next();
}

 

转载自: http://www.leyond.info/usage-of-foreach-in-java/#more-131521

 

更多关于foreach的神秘资料,

 

参考:http://caterpillar.onlyfun.net/Gossip/JavaEssence/Foreach.html ,本文还参考了:

  1. http://yczhuang.blogspot.com/2009/02/javaforeach.html
  2. http://leepoint.net/notes-java/flow/loops/foreach.html
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值