若是咱们用Java作开发的话,最经常使用的容器之一就是List集合了,而List集合中用的较多的就是ArrayList 和 LinkedList 两个类,这二者也常被用来作比较。由于最近在学习Java的集合类源码,对于这两个类天然是不能放过,因而乎,翻看他们的源码,我发现,ArrayList实现了一个叫作 RandomAccess
的接口,而 LinkedList 是没有的,java
public class ArrayList<E> extends AbstractList<E> implements List<E>, RandomAccess, Cloneable, java.io.Serializable
public class LinkedList<E> extends AbstractSequentialList<E> implements List<E>, Deque<E>, Cloneable, java.io.Serializable
打开源码后,发现接口里面什么也没有,这是个空的接口,而且是1.4才引入的dom
* @since 1.4 */ public interface RandomAccess { }
那么这个接口是作什么的?oop
经过官网的API,我才知道,原来这是一个标志接口,下面引入一段官网的原文:性能
public interface RandomAccess学习
Marker interface used by
List
implementations to indicate that they support fast (generally constant time) random access.测试
这段话大概的意思就是说 RandomAccess 是一个标志接口,代表实现这个这个接口的 List 集合是支持快速随机访问的。也就是说,实现了这个接口的集合是支持 快速随机访问 策略的。this
同时,官网还特地说明了,若是是实现了这个接口的 List,那么使用for循环的方式获取数据会优于用迭代器获取数据。code
As a rule of thumb, a
List
implementation should implement this interface if, for typical instances of the class, this loop:接口 for (int i=0, n=list.size(); i < n; i++)
list.get(i);开发 for (Iterator i=list.iterator(); i.hasNext(); )
i.next();
下面作个测试吧,以ArrayList 为例。
分别建立两个方法,一个用for循环 get() 数据的方式遍历集合,另外一个是用迭代器,分别返回所用的时间:
public static long arrayFor() { List<Integer> list = new ArrayList<Integer>(); for (int i = 1; i <= 100000; i++) { list.add(i); } //开始时间 long startTime = System.currentTimeMillis(); for (int j = 0; j < list.size(); j++) { Object num = list.get(j); } //结束时间 long endTime = System.currentTimeMillis(); //返回所用时间 return endTime-startTime; } public static long arrayIterator() { List<Integer> list = new ArrayList<Integer>(); for (int i = 1; i <= 100000; i++) { list.add(i); } long startTime = System.currentTimeMillis(); Iterator iterator = list.iterator(); while (iterator.hasNext()){ Object next = iterator.next(); } long endTime = System.currentTimeMillis(); return endTime-startTime; }
接着,在mian方法中测试:
public static void main(String[] args) { long time1 = arrayFor(); long time2 = arrayIterator(); System.out.println("ArrayList for循环所用时间=="+time1); System.out.println("ArrayList 迭代器所用时间=="+time2); }
运行程序,输出结果
ArrayList for循环所用时间==2 ArrayList 迭代器所用时间==3
能够看出,for循环遍历元素时间上是少于迭代器的,证实RandomAccess 接口确实是有这个效果。
固然,如今的语言和机器性能这么高,两种方式遍历数据的性能差距几乎能够忽略不计,尤为是数据量不大的状况下。因此,我以为,平常使用中不必过度追求哪一种方式好,按照本身的习惯来就行。