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

来源:互联网 发布:制作网页用什么软件 编辑:程序博客网 时间:2024/05/18 20:32
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存入整型afor (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