关于ArrayList和LinkList的RandomAccess

本文探讨了Java中List集合的两种实现:ArrayList与LinkedList,重点解析了ArrayList实现的RandomAccess接口,通过实验证明了在for循环遍历数据方面,ArrayList相比LinkedList具有更高的效率。

引出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 &lt; 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 接口确实是有这个效果。

最后

当然,现在的语言和机器性能这么高,两种方式遍历数据的性能差距几乎可以忽略不计,尤其是数据量不大的情况下。所以,我觉得,日常使用中没必要过分追求哪种方式好,按照自己的习惯来就行。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值