jdk 1.4提供RandomAccess接口,那么它怎么用你知道吗?
先看个例子
import java.time.Instant; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; public class RandomAccessTest { public static void main(String[] args) { List<Integer> list = new ArrayList(); List<Integer> list2 = new LinkedList(); long s = Instant.now().toEpochMilli(); for(int i=0;i<100000;i++){ list.add(i); list2.add(i); } System.out.println("实现RandomAccess接口"); long e = Instant.now().toEpochMilli(); System.out.println("创建数组时间是:"+(e-s)+"毫秒"); s = Instant.now().toEpochMilli(); for(int i=0;i<100000;i++){ list.get(i); } e = Instant.now().toEpochMilli(); System.out.println("for循环遍历时间是:"+(e-s)+"毫秒"); s = Instant.now().toEpochMilli(); Iterator<Integer> it = list.iterator(); while (it.hasNext()){ it.next(); } e = Instant.now().toEpochMilli(); System.out.println("迭代器遍历时间是:"+(e-s)+"毫秒"); System.out.println("============"); System.out.println("未实现RandomAccess接口"); s = Instant.now().toEpochMilli(); for(int i=0;i<100000;i++){ list2.get(i); } e = Instant.now().toEpochMilli(); System.out.println("for循环遍历时间是:"+(e-s)+"毫秒"); s = Instant.now().toEpochMilli(); Iterator<Integer> it2 = list2.iterator(); while (it.hasNext()){ it2.next(); } e = Instant.now().toEpochMilli(); System.out.println("迭代器遍历时间是:"+(e-s)+"毫秒"); } }运行结果
说明原因先看下源码
ArrayList实现了RandomAccess接口
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.SerializableLinkedList未实现RandomAccess接口
public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, java.io.SerializableRandomAccess接口
public interface RandomAccess {
}
结论 实现了RandomAccess接口的集合,用for循环遍历效率高,没实现RandomAccess接口用迭代器遍历效率高。
注意 增强for循环底层也是采用迭代器实现,所以增强for循环和迭代器遍历是一回事。