for循环 和 增强for循环for each

package collection;
/**
 * JDK1.5之后推出了一个新特性:
 * 增强型for循环,也称为新循环,for each
 * 
 * 新循环不用来替代传统循环的工作,它只用来遍历集合或数组
 * 
 * 新循环是编译器认可,而非虚拟机
 * 
 * @author 清风已来
 *
 */

public class NewforDome {
	public static void main(String[] args) {
		String [] arr = {"one","two","three","four"};
		for(int i=0;i<arr.length;i++) {
			String str=arr[i];
			System.out.println(str);
		}
		for(String str:arr) {
			System.out.println(str);
		}
		
	}

}

===========================用for each遍历集合元素=======================================

package collection;

import java.util.ArrayList;
import java.util.Collection;

/**
* 使用新循环遍历集合
*
* @author 清风已来
*
*/

public class NewforDome {
public static void main(String[] args) {
Collection c= new ArrayList();
c.add("one");
c.add("two");
c.add("three");
c.add("four");
c.add("five");
c.add("six");
c.add("seven");

for(Object o:c) {
String str =(String)o;
System.out.println(str);

}

}
}

posted @ 2018-01-12 14:27  清风已来  阅读(224)  评论(0编辑  收藏  举报