zoukankan      html  css  js  c++  java
  • 三种迭代Java ArrayList方法及比较

    闲来无事,研究一下Java Collection,首先是ArrayList。

    通过三种方式遍历了长度为100000的ArrayList。

    import java.util.*;
    
    public class CollectionTest {
        public static void main(String[] args) {
            List<Integer> list = new ArrayList<Integer>();
            for (int i = 0 ; i < 100000 ; i++) {
                list.add(i);
            }
            // 第一种遍历list的方式
            System.out.println("-------------foreach--------------------");
            long t1 = System.currentTimeMillis();
            for(int str: list) {
                System.out.println(str);
            }
            long t2 = System.currentTimeMillis();
            // 第二种遍历list的方式
            System.out.println("-------------------toArray-----------------");
            Integer[] array = new Integer[list.size()];
            list.toArray(array);
            long t3 = System.currentTimeMillis();
            for (int i = 0; i < array.length; i++) {
                System.out.println(array[i]);
            }
            long t4 = System.currentTimeMillis();
    
            // 第三种遍历list的方式
            System.out.println("--------------Iterator-----------------");
            Iterator<Integer> it = list.iterator();
            long t5 = System.currentTimeMillis();
            while (it.hasNext()) {
                System.out.println(it.next());
            }
            long t6 = System.currentTimeMillis();
    
            long t12 = t2 - t1;
            long t34 = t4 - t3;
            long t56 = t6 - t5;
            System.out.println(t12);
            System.out.println(t34);
            System.out.println(t56);
        }
    }

    运行的结果为1104,978,658

    可以发现,使用Iterator最快,toArray次之,forEach最慢。

  • 相关阅读:
    Sum Root to Leaf Numbers
    Sum Root to Leaf Numbers
    Sort Colors
    Partition List
    Binary Tree Inorder Traversal
    Binary Tree Postorder Traversal
    Remove Duplicates from Sorted List II
    Remove Duplicates from Sorted List
    Search a 2D Matrix
    leetcode221
  • 原文地址:https://www.cnblogs.com/cangqinglang/p/10031866.html
Copyright © 2011-2022 走看看