javaSE Iterable接口,增强for循环,遍历数组/集合

增强for循环,遍历数组/集合 (Iterable接口的实现类)
好处: 代码少了,方便对容器遍历
弊端: 没有索引,不能使用索引进行定位修改。


Demo.java:

package cn.xxx.demo;
import java.util.ArrayList;
import java.util.Collection;

/*
 *  JDK1.5新特性,增强for循环
 *  JDK1.5版本后,出现新的接口 java.lang.Iterable
 *    Collection开始继承Iterable接口
 *    Iterable作用,实现增强for循环
 *    
 *  增强for循环,遍历数组/集合 (Iterable接口的实现类)
 *  好处: 代码少了,方便对容器遍历
 *  弊端: 没有索引,不能使用索引进行定位修改。
 */

public class Demo {
	public static void main(String[] args) {
		function_1();
	}

	public static void function_1(){
		Collection<String> coll = new ArrayList<String>();
		coll.add("123");
		coll.add("456");
		for(String s : coll){    // 增强for循环遍历集合Collection (底层由集合的Iterator迭代器实现)
			System.out.println(s);
		}
	}

	public static void function(){
		int[] arr = {3,1,9,0};
		for(int item : arr){   // 增强for循环遍历数组
			System.out.println(item);
		}
	}
}


猜你喜欢

转载自blog.csdn.net/houyanhua1/article/details/80653212
今日推荐