您好,登錄后才能下訂單哦!
java 中RandomAccess接口源碼分析
RandomAccess是一個接口,位于java.util包中。
這個接口的作用注釋寫的很清楚了:
/** * 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. * List實現所使用的標記接口,用來表明實現了這些接口的list支持快速(通常是常數時間)隨機訪問。 * 這個接口的主要目的是允許一般的算法更改它們的行為,以便在隨機或者順序存取列表時能提供更好的性能。 * <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. * 操作隨機訪問列表(如ArrayList)的最佳算法在應用于順序存取列表時,有可能產生二次項行為。 * 泛型算法列表鼓勵在將某個算法應用于順序存取列表可能導致差的性能之前,先檢查給定的列表是否是這個接口的一個實例, * 并在需要時去改變這些算法的行為以保證性能。 * <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: * 隨機訪問和順序存取之間的界限通常是模糊的。例如,一些List實現在變得很大時會導致漸進的非線性訪問時間,但實際上是常量訪問時間。 * 這樣的List實現通常都應該實現該接口。 * 一般來說,某個List實現如果(對某些典型的類的實例來說)滿足下面的條件,就應該實現這個接口:循環 * <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" rel="external nofollow" > * Java Collections Framework</a>. * 這個接口是Java集合框架的一員。 * @since 1.4 */ public interface RandomAccess { }
RandomAccess是一個空接口,而空接口的作用一般是起到一個標識的作用。
通俗點講,就是判斷一個list是否實現了RandomAcess接口,如果實現了,采用下面所示的簡單的for循環進行訪問速度比較快:
for (int i=0, n=list.size(); i < n; i++) list.get(i);
如果未實現RandomAcess接口,則采用下面的iterator循環訪問速度比較快。
for (Iterator i=list.iterator(); i.hasNext(); ) i.next();
判斷使用instanceof,即
if (list instanceof RandomAccess)
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。