JDK 1.5给我们提供了另外一种for循环;FOR增强
优点:对于遍历Array和Collection等集合的时候非常的便捷
缺点:不能够访问数组的下标,FOR增强语句与一般语句相比
不能很方便的移除集合中的元素,与Iterator相比remove()
FOR增强的语句一般指适合做简单的遍历使用,其它时间段不建议使用
下面是使用FOR增强来遍历元素的例子:
package Collection;
import java.util.*;
public class forTest<E> {
public static void main(String[] args) {
Collection<String> test = new ArrayList<String>();
//使用for循环来增加五个元素
for(int i = 0;i<5;i++){
test.add("元素"+i);
}
//使用for增强来遍历元素
//将test集合中的元素一个一个的遍历到String s中来
for(String s:test){
//将s读取到的元素输出
System.out.println(s);
}
}
}
运算结果:
元素0
元素1
元素2
元素3
元素4