java中for循环和迭代器哪个效率高?

如题所述

java中迭代器效率高

ArrayList实现了RandomAccess接口,RandomAccess接口为ArrayList带来了什么好处呢?

我们查看一下RandomAccess的源码文档,发现有这样一段描述:

As a rule of thumb, a List implementation should implement this interface if, for typical instances of the class, this loop:

for (int i=0, n=list.size(); i < n; i++)
list.get(i);

runs faster than this loop:

for (Iterator i=list.iterator(); i.hasNext(); )
i.next();

从描述中,可以看出实现RandomAccess接口的集合类,使用for循环的效率会比Iterator高。

RandomAccess接口为ArrayList带来的好处:

    1、可以快速随机访问集合。

    2、使用快速随机访问(for循环)效率可以高于Iterator。

温馨提示:答案为网友推荐,仅供参考
相似回答