使用foreach循环遍历集合元素
- Java5.0 提供了foreach循环迭代访问Collection和数组
- 遍历操作不需要获取Collection或数组的长度,无需使用索引访问元素
- 遍历集合的底层调用Iterator完成操作
- foreach还可以用来遍历数组
代码实现
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
public class ForTest {
public static void main(String[] args) {
Collection coll = new ArrayList();
coll.add(123);
coll.add(new Date());
coll.add("heipapap");
coll.add("baibai");
coll.add(false);
coll.add(new Person("Tom",23));
coll.add(new Person("maruya",23));
for(Object obj:coll){
System.out.println(obj);
}
int[] arr = new int[]{1,2,3,4,5,6,7,8};
for(int i :arr){
System.out.println(i);
}
String[] str = new String[]{"gege","gege","gege"};
for(int i =0;i<str.length;i++){
str[i]="woc";
}
for(int i =0;i<str.length;i++){
System.out.println(str[i]);
}
for(String s : str){
s = "hahaha";
}
for(int i =0;i<str.length;i++){
System.out.println(str[i]);
}
}
}