foreach遍历的实质

foreach遍历效率低于普通的遍历方式,而且在遍历Arraylist时访问结果会出现乱序。

在写代码时遇到输出乱序,做此笔记,部分代码:

//foreach是随机遍历
    public static void main(String[] args) {
        int[][] sampleBlock = {{1,2,3,4},{1,2,3,4},{1,2,3,4},{1,2,3,4}};
        int[][] bMatrix = {{0,0,1,1},{0,0,1,1},{0,1,1,1},{0,0,1,1}};
        LinkedList<Integer> res = getBoundary(sampleBlock, bMatrix);
        System.out.println("普通遍历");
        for(int i = 0;i < res.size();i++){
            System.out.print(res.get(i) + " ");
        }
        System.out.println("foreach遍历");
        for (Integer integer : res) {
            System.out.print(res.get(integer) + " ");
        }
    }

参考:http://blog.csdn.net/hui_lang/article/details/7528358
假设现在我们要求一个 List 实例的平均值,我们可以通过如下两种方法进行计算(这里假设我们传入的是ArrayList 对象):

    1. 通过 foreach 方式遍历列表计算平均值

[java] view plaincopyprint?
public static int average(List list) {
int sum = 0;
// 遍历求和
for (int i : list) {
sum += i;
}
return sum / list.size();
}
2. 通过下标方式访问列表计算平均值

[java] view plaincopyprint?
public static int average(List list) {
int sum = 0;
// 遍历求和
for (int i = 0, size = list.size(); i < size; i++) {
sum += i;
}
return sum / list.size();
}
大家可能都觉得上面两种实现方式只是写法上不同,但执行过程是一样的。对于处理小数量的数据,它们在效率上相差并不大,但对于处理大数量的数据,后者要比前者要高效很多。比如处理 100万条数据,前者执行大概需要 42ms,后者只需要 25ms(在自己电脑上测试结果)。那为什么使用下标方式遍历数组会有这么高的性能提升呢?

    我们知道,Java 中的 foreach 语法是 iterator(迭代器)的变形用法(可以看看反编译之后的代码),也就是说上面的 foreach 与下面的代码等价:

[java] view plaincopyprint?
for (Iterator i = list.iterator(); i.hasNext();) {
sum += ((Integer)iterator.next()).intValue();
}
lsit.iterator() 返回的迭代器对象是什么呢?查看JDK源码知道,ArrayList 类继承于 AbstractList 类,AbstracList 对 iterator 方法实现如下(ArrayList 类并没有重写该方法):

[java] view plaincopyprint?
public Iterator iterator() {
return new Itr();
}
方法直接创建一个 Itr 对象并将其返回,Itr 类其实是 AbstractList 类的一个内部类,Itr 类实现了 Iterator 接口,Itr 类部分源代码如下:
[java] view plaincopyprint?
private class Itr implements Iterator {
/**
* Index of element to be returned by subsequent call to next.
*/
int cursor = 0;

/** 
 * Index of element returned by most recent call to next or 
 * previous.  Reset to -1 if this element is deleted by a call 
 * to remove. 
 */  
int lastRet = -1;  

public boolean hasNext() {  
    return cursor != size();  
}  

public E next() {  
    checkForComodification();  
    try {  
        E next = get(cursor);  
        lastRet = cursor++;  
        return next;  
    } catch (IndexOutOfBoundsException e) {  
        checkForComodification();  
        throw new NoSuchElementException();  
    }  
}  

}
从上面代码可以看出,迭代器同样也是通过对指向数组(ArrayList 是通过数组实现的)的下标进行递增来遍历整个数组的,这和通过下标方式访问列表计算平均值的方法是一样的,但是区别在于,迭代器需要调用 hasNext() 函数来判断指向数组的下标是否移到了数组末尾,而下标访问方式中并不需要对此进行检查;除此之外,在迭代器的 next() 方法中也出现了下标访问方式没有的 checkForComodification() 方法和 lastRet 变量赋值操作。这也就是通过 foreach 方式遍历耗时的原因。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值