关于RandomAccess接口

ArrayList 和 LinkedList 两个类,这两者常被用来做比较,翻看他们的源码,发现ArrayList实现了一个叫做 RandomAccess 的接口,而 LinkedList 没有的。。。

 

 

打开源码后,发现接口里面什么也没有,这是个空的接口。。。

 

 

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

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

public interface RandomAccess Marker interface used by List implementations to indicate that they support fast (generally constant time) random access.

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

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

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();
}

 

posted @ 2020-08-04 17:29  zero_7  阅读(229)  评论(0编辑  收藏  举报