引出RandomAccess接口
背景
如果我们用Java做开发的话,最常用的容器之一就是List集合了,而List集合中用的较多的就是ArrayList 和 LinkedList 两个类,这两者也常被用来做比较。因为最近在学习Java的集合类源码,对于这两个类自然是不能放过,于是乎,翻看他们的源码,我发现,ArrayList实现了一个叫做 RandomAccess 的接口,而 LinkedList 是没有的,
什么是 RandomAccess(官方解释):
* <p>It is recognized that the distinction between random and sequential
* access is often fuzzy. For example, some <tt>List</tt> implementations
* provide asymptotically linear access times if they get huge, but constant
* access times in practice. Such a <tt>List</tt> implementation
* should generally implement this interface. As a rule of thumb, a
* <tt>List</tt> implementation should implement this interface if,
* for typical instances of the class, this loop:
* <pre>
* for (int i=0, n=list.size(); i < n; i++)
* list.get(i);
* </pre>
* runs faster than this loop:
* <pre>
* for (Iterator i=list.iterator(); i.hasNext(); )
* i.next();
* </pre>
*
RandomAccess
- RandomAccess 简称 快速随机访问 策略;
- 使用了这个接口的List,那么使用for循环的方式获取数据会优于用迭代器获取数据。
实际测试
接着,在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 接口确实是有这个效果。
最后
当然,现在的语言和机器性能这么高,两种方式遍历数据的性能差距几乎可以忽略不计,尤其是数据量不大的情况下。所以,我觉得,日常使用中没必要过分追求哪种方式好,按照自己的习惯来就行。