RandomAccess
- List实现了该接口,说明该实现类的数据可以进行随机访问,不需要保证顺序性.比如ArrayList实现了该接口,LinkedList没有实现该接口.
- 随机访问列表使用循环遍历,顺序访问列表使用迭代器遍历。
JDK定义
/**
* Marker interface used by <tt>List</tt> 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.
*
* <p>The best algorithms for manipulating random access lists (such as
* <tt>ArrayList</tt>) can produce quadratic behavior when applied to
* sequential access lists (such as <tt>LinkedList</tt>). Generic list
* algorithms are encouraged to check whether the given list is an
* <tt>instanceof</tt> 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.
*
* <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>
*
* <p>This interface is a member of the
* <a href="{@docRoot}/../technotes/guides/collections/index.html">
* Java Collections Framework</a>.
*
* @since 1.4
*/
- List的实现类使用的标记接口,一般来标识该实现类能够支持快速随机访问.
- 接口存在的目的:继承该接口的实现类,能够允许一般的算法来更改他们的行为,yibian在随机或者循环访问列表时,能够提供更好的性能.
- 对于随机访问的列表(ArrayList)的操作方法应用到顺序访问的列表(LinkedList),将会产生二次项行为(个人理解应该是额外的操作吧).所以,对不同访问类型的列表,我们需要采用最为合适的算法.
- 总结来讲,随机访问类型的列表进行loop遍历的时间更短,顺序访问类型的列表通过Iterator进行遍历的时间更短.
参考文章:RandomAccess 接口使用