JDK源码-RandomAccess

RandomAccess

  • List实现了该接口,说明该实现类的数据可以进行随机访问,不需要保证顺序性.比如ArrayList实现了该接口,LinkedList没有实现该接口.
  • 随机访问列表使用循环遍历,顺序访问列表使用迭代器遍历。

JDK定义

/**
 * Marker interface used by List implementations to indicate that
 * they support fast (generally constant time) random access.  The primary
 * purpose of this interface is to allow generic algorithms to alter their
 * behavior to provide good performance when applied to either random or
 * sequential access lists.
 *
 * 

The best algorithms for manipulating random access lists (such as * ArrayList) can produce quadratic behavior when applied to * sequential access lists (such as LinkedList). Generic list * algorithms are encouraged to check whether the given list is an * instanceof this interface before applying an algorithm that would * provide poor performance if it were applied to a sequential access list, * and to alter their behavior if necessary to guarantee acceptable * performance. * *

It is recognized that the distinction between random and sequential * access is often fuzzy. For example, some List implementations * provide asymptotically linear access times if they get huge, but constant * access times in practice. Such a List implementation * should generally implement this interface. 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);
 * 
* runs faster than this loop: *
 *     for (Iterator i=list.iterator(); i.hasNext(); )
 *         i.next();
 * 
* *

This interface is a member of the * * Java Collections Framework. * * @since 1.4 */

  • List的实现类使用的标记接口,一般来标识该实现类能够支持快速随机访问.
  • 接口存在的目的:继承该接口的实现类,能够允许一般的算法来更改他们的行为,yibian在随机或者循环访问列表时,能够提供更好的性能.
  • 对于随机访问的列表(ArrayList)的操作方法应用到顺序访问的列表(LinkedList),将会产生二次项行为(个人理解应该是额外的操作吧).所以,对不同访问类型的列表,我们需要采用最为合适的算法.
  • 总结来讲,随机访问类型的列表进行loop遍历的时间更短,顺序访问类型的列表通过Iterator进行遍历的时间更短.
    参考文章:RandomAccess 接口使用

你可能感兴趣的:(JDK源码-RandomAccess)