JDK源碼-RandomAccess

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 &lt; 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 接口使用
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • 一.線性表 定義:零個或者多個元素的有限序列。也就是說它得滿足以下幾個條件:??①該序列的數據元素是有限的。??②...
    Geeks_Liu閱讀 2,710評論 1 12
  • Java源碼研究之容器(1) 如何看源碼 很多時候我們看源碼, 看完了以后經常也沒啥收獲, 有些地方看得懂, 有些...
    駱駝騎士閱讀 1,006評論 0 22
  • 前言 今天來介紹下LinkedList,在集合框架整體框架一章中,我們介紹了List接口,LinkedList與A...
    嘟爺MD閱讀 3,627評論 11 37
  • 在經過一次沒有準備的面試后,發現自己雖然寫了兩年的android代碼,基礎知識卻忘的差不多了。這是程序員的大忌,沒...
    猿來如癡閱讀 2,866評論 3 10
  • 本文參加#未完待續,就要表白#活動,本人承諾,文章內容為原創,且未在其他平臺發表過。 我是來自山間的水,一抹溪流,...
    山榆何多閱讀 302評論 3 18