我想比较一下用Iterator、for语句、foreach来遍历LinkedList,谁的速度快。于是写了如下代码:
package mystudy; import java.util.*; public class MyStudy { private static final int SIZE = 100000; private Integer[] arr = new Integer[SIZE]; private AbstractList<Integer> absList; public void initialize(){ LinkedList<Integer> list = new LinkedList<Integer>(); for (int i = 0; i < SIZE; i ++){ arr[i] = i; list.add(i); } absList = (AbstractList<Integer>)list.subList(0, list.size()); } public void method0(){ Integer tmp; for (int i = SIZE - 1; i >= 0; i --){ tmp = arr[i]; } } public void method1(){ ListIterator<Integer> it = absList.listIterator(SIZE); Integer tmp; while(it.hasPrevious()){ tmp = it.previous(); } } public void method2(){ Integer tmp; for (int i = SIZE - 1; i >= 0; i --){ tmp = absList.get(i); } } public void method3(){ Integer tmp; for(Integer i : absList){ tmp = i; } } public static void main(String[] args){ MyStudy study = new MyStudy(); study.initialize(); long start,expend0,expend1,expend2,expend3; start = System.currentTimeMillis(); study.method0(); expend0 = System.currentTimeMillis() - start; start = System.currentTimeMillis(); study.method1(); expend1 = System.currentTimeMillis() - start; start = System.currentTimeMillis(); study.method2(); expend2 = System.currentTimeMillis() - start; start = System.currentTimeMillis(); study.method3(); expend3 = System.currentTimeMillis() - start; System.out.println("expend0:" + expend0 + " expend1:" + expend1 + " expend2:" + expend2 + " expend3:" + expend3); } }
运行的结果:
expend0:1 expend1:7 expend2:5548 expend3:7
可见用for语句遍历LinkedList是最慢的。
时间: 2024-11-12 07:36:55