java LinkedList与ArrayList遍历问题
package test; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class TestList { static final int size = 100000; public static void main(String[] args) { List<Integer> linkedList = new LinkedList<Integer>(); List<Integer> arrayList = new ArrayList<Integer>(); long startTime; long endTime; Iterator<Integer> iterator; //添加数据 for (int i = 0; i < size; i++) { int value = (int) (Math.random() * 100); linkedList.add(value); } arrayList.addAll(linkedList); startTime = System.currentTimeMillis(); for (int i = 0; i < linkedList.size(); i++) { Integer value = linkedList.get(i); } endTime = System.currentTimeMillis(); System.out.println("下标方法遍历LinkedList 耗时" + (endTime - startTime) + "ms"); startTime = System.currentTimeMillis(); for (Integer value : linkedList) { } endTime = System.currentTimeMillis(); System.out.println("增强for方法遍历LinkedList 耗时" + (endTime - startTime) + "ms"); startTime = System.currentTimeMillis(); iterator = linkedList.iterator(); while (iterator.hasNext()) { Integer value = iterator.next(); } endTime = System.currentTimeMillis(); System.out.println("迭代器方法遍历LinkedList 耗时" + (endTime - startTime) + "ms"); System.out.println(); startTime = System.currentTimeMillis(); for (int i = 0; i < arrayList.size(); i++) { Integer value = arrayList.get(i); } endTime = System.currentTimeMillis(); System.out.println("下标方法遍历ArrayList 耗时" + (endTime - startTime) + "ms"); startTime = System.currentTimeMillis(); for (Integer value : arrayList) { } endTime = System.currentTimeMillis(); System.out.println("增强for方法遍历ArrayList 耗时" + (endTime - startTime) + "ms"); startTime = System.currentTimeMillis(); iterator = arrayList.iterator(); while (iterator.hasNext()) { Integer value = iterator.next(); } endTime = System.currentTimeMillis(); System.out.println("迭代器方法遍历ArrayList 耗时" + (endTime - startTime) + "ms"); } }
结果如下:
下标方法遍历LinkedList 耗时3771ms
增强for方法遍历LinkedList 耗时2ms
迭代器方法遍历LinkedList 耗时1ms
下标方法遍历ArrayList 耗时2ms
增强for方法遍历ArrayList 耗时2ms
迭代器方法遍历ArrayList 耗时1ms
结论:
1、对ArrayList,三种遍历方法效率差别不大;
2、对LinkedList,下标方法遍历最慢,增强for方法和迭代器方法遍历效率相对高