使用foreach循环遍历集合元素

使用foreach循环遍历集合元素

  1. Java5.0 提供了foreach循环迭代访问Collection和数组
  2. 遍历操作不需要获取Collection或数组的长度,无需使用索引访问元素
  3. 遍历集合的底层调用Iterator完成操作
  4. foreach还可以用来遍历数组
    在这里插入图片描述
代码实现
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
/*
 * jdk5.0新增了foreach循环,用于遍历集合,数组
 */
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(集合元素的类型 局部变量 : 集合对象)
		//内部仍然调用了迭代器
		for(Object obj:coll){
			System.out.println(obj);
		}
		
		int[]  arr = new int[]{1,2,3,4,5,6,7,8};
		//for(数组元素的类型 局部变量 :数组对象)
		for(int i :arr){
			System.out.println(i);
		}
		
		//通过一个练习题来理解一下增强for循环和普通for循环的区别
		//方式一 普通for循环
		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]);
			//woc
			//woc
			//woc
		}
		//方式二:增强for循环
		for(String s : str){
			s = "hahaha";
		}
		//遍历
		for(int i =0;i<str.length;i++){
			System.out.println(str[i]);
			//woc
			//woc
			//woc
		}
	}
}

发布了70 篇原创文章 · 获赞 8 · 访问量 3272

猜你喜欢

转载自blog.csdn.net/gldbys/article/details/105053239