[code]
package com.testenhanced;
import java.util.* ;
import java.util.Collection;
public class TestEnhanced {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = {1,2,3,4,5,6} ;
for(int i: arr) {
System.out.println(i) ;
}
Collection c = new ArrayList() ;
c.add(new String ("asd")) ;
c.add(new String ("lmn")) ;
c.add(new String("156")) ;
for(Object o: c) {
System.out.println(o) ;
}
}
}
[/code]
[code]
console:
1
2
3
4
5
6
asd
lmn
156
[/code]
//[color=red]除了简单遍历并读出其中的内容外,不建议使用增强for[/color]
package com.testenhanced;
import java.util.* ;
import java.util.Collection;
public class TestEnhanced {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
int[] arr = {1,2,3,4,5,6} ;
for(int i: arr) {
System.out.println(i) ;
}
Collection c = new ArrayList() ;
c.add(new String ("asd")) ;
c.add(new String ("lmn")) ;
c.add(new String("156")) ;
for(Object o: c) {
System.out.println(o) ;
}
}
}
[/code]
[code]
console:
1
2
3
4
5
6
asd
lmn
156
[/code]
//[color=red]除了简单遍历并读出其中的内容外,不建议使用增强for[/color]
本文通过两个示例展示了Java中增强for循环的基本用法:一是遍历整型数组,二是遍历字符串对象集合。虽然增强for循环简化了代码书写,但文章提醒读者在需要修改集合元素时不宜采用此循环。
1011

被折叠的 条评论
为什么被折叠?



