java迭代器和for循环优劣详解

 更新时间:2021年1月22日 10:00  点击:2298

在进行迭代的时候,程序运行的效率也是我们挑选迭代方法的重要原因。目前有三种迭代方法:for循环、迭代器和Foreach。前两者相信大家都非常熟悉,为了更加直观分析效率的不同,我们还加入Foreach一起比较。下面我们就三种方法的概念进行理解,然后ArrayList中探索三种方法的效率。

1.概念理解

for循环:是支持迭代的一种通用结构,是最有效,最灵活的循环结构

迭代器:是通过集合的iterator()方法得到的,所以我们说它是依赖于集合而存在的

Foreach:通过阅读源码我们还发现一个Iterable接口。它包含了一个产生Iterator对象的iterator()方法,而且将Iterator对象被foreach用来在序列中移动。对于任何实现Iterable接口的对象都可以使用。

2.效率实例

ArrayList中的效率对比:

    List<Integer> integers = Lists.newArrayList();
    for(int i=0;i<100000;i++){
      integers.add(i);
    }
    long start1 = System.currentTimeMillis();
    for(int count =0 ;count<10;count++){
      for(int i=0;i<integers.size();i++){
        int j=integers.get(i);
      }
    }
    System.out.println(String.format("for循环100次时间:%s ms",System.currentTimeMillis()-start1));
    long start2 = System.currentTimeMillis();
    for(int count =0 ;count<10;count++) {
      for (Integer i : integers) {
        int j = i;
      }
    }
    System.out.println(String.format("foreach循环100次时间:%s ms",System.currentTimeMillis()-start2));
    long start3 = System.currentTimeMillis();
    for(int count =0 ;count<10;count++) {
      Iterator<Integer> iterator = integers.iterator();
      while(iterator.hasNext()){
        int j=iterator.next();
      }
    }
    System.out.println(String.format("迭代器循环100次时间:%s ms",System.currentTimeMillis()-start3));

结果:

for循环100次时间:15 ms

foreach循环100次时间:25 ms

迭代器循环100次时间:20 ms

知识点扩展:

增强for循环:foreach

在Java 5.0提供了一种新的迭代访问 Collection和数组的方法,就是foreach循环。使用foreach循环执行遍历操作不需获取Collection或数组的长度,也不需要使用索引访问元素。

到此这篇关于java迭代器和for循环优劣详解的文章就介绍到这了,更多相关分析java迭代器和for循环优劣内容请搜索猪先飞以前的文章或继续浏览下面的相关文章希望大家以后多多支持猪先飞!

[!--infotagslink--]

相关文章