Java集合类:“随机访问”的RandomAccess接口

引出RandomAccess接口

如果我们用Java做开发的话,最常用的容器之一就是List集合了,而List集合中用的比较多的就是ArrayList和LinkedList两个类了。这两个也常用来做比较。因为最近在学习Java的集合类源码,对于这两个类自然是不能放过的。于是乎,翻看他们的源码,我发现,ArrayList实现了一个叫做 RandomAccess 的接口,而LinkedList是没有的。

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才引入的。

* @since 1.4
 */
public interface RandomAccess {
}

那么这个接口是做什么的?

标志接口(Marker Interface)

通过官网的API,我才知道,原来是一个标志接口,下面引入一段官网的原文:

Marker interface used by <tt>List</tt> implementations to indicate that they support fast (generally constant time) random access.

这段话的大概意思就是说RandomAccess是一个标志接口,表明实现这个接口的List集合是支持快速随机访问的。也就是说,实现了这个接口的集合是支持快速随机访问策略的。

同时,官网还特意说明了,如果是实现了这个接口的List,那么使用for循环的方式获取数据会优于用迭代器获取数据。

As a rule of thumb, aList 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();

下面做一个测试吧。

import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class Study {
    
    public static long arrayFor() {
        List<Integer> list = new ArrayList<Integer>();
        for(int i =1;i<=1000000;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<=1000000;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;
    }
    public static void main(String[] args) {
        long time_for = arrayFor();
        long time_iter = arrayIterator();
        System.out.println("ArrayList for循环所用的时间=="+time_for);
        System.out.println("ArrayList 迭代器所用的时间=="+time_iter);
    }

}

输出结果为:

ArrayList for循环所用的时间==5
ArrayList 迭代器所用的时间==7

可以看出,for循环遍历袁术时间上是少于迭代器的,证明RandomAccess接口确实是有这个效果的。

原文地址:https://www.cnblogs.com/LoganChen/p/12347512.html