JAVA学习代码——增强for循环For each

import java.util.LinkedList;
import java.util.List;

/**
 * 增强for循环使用:增强for循环和iterator遍历的效果是一样的,
 * 也就说增强for循环的内部也就是调用iteratoer实现的
/*foreach并不是java关键字,是for语句的特殊简化版本,在遍历数组,集合时,
	 * foreach更简单快捷。字面意思“for每一个”
	 *语法:for(元素类型 元素变量:遍历对象){执行的代码}
	 *分别使用for和foreach语句来遍历数组 */
 */
public class For_each {
	//增强for循环释义
	public void For_each1() {
		int[] b = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
		// for循环遍历数组b存入整型a
		for (int a : b) {
			System.out.println(a);
		}
	}
	
	//增强for循环与for循环比较
	public void For_each2() {
		// List<Integer> list = new ArrayList<Integer>();
		List<Integer> list = new LinkedList<Integer>();
		//for循环
		for (int i = 0; i < 50000; i++) {
			list.add(11);
		}
		int resutl = 0;
		long start1 = System.currentTimeMillis();
		for (int i = 0; i < list.size(); i++) {
			resutl = list.get(i);
		}
		System.out.println("普通循环使用了" + (System.currentTimeMillis() - start1) + "毫秒");

		long start2 = System.currentTimeMillis();
		//增强for循环
		for (int c2 : list) {
		}
		System.out.println("增强for循环使用了" + (System.currentTimeMillis() - start2) + "毫秒");
	}

	 public static void main(String[] args) {
		 For_each run = new For_each();
		 run.For_each1();
		 run.For_each2();
	 }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值