Java中RandomAccess接口簡(jiǎn)介

在閱讀ArrayList的源碼時(shí),你會(huì)發(fā)現(xiàn)這樣一個(gè)接口:RandomAccess。接下來(lái)讓我們探索一下這個(gè)接口。

首先,這是一個(gè)標(biāo)識(shí)性接口,不包含實(shí)際方法。官方API中的介紹如下:

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.

也就是說(shuō),這個(gè)接口在List具體實(shí)現(xiàn)中的主要作用是用來(lái)指出該實(shí)現(xiàn)支持快速隨機(jī)訪問(wèn),從而,可以使得某些通用算法可以根據(jù)某些實(shí)現(xiàn)是否支持快速隨機(jī)訪問(wèn)來(lái)修改算法行為以提高性能。

官方API中還特別指出,實(shí)現(xiàn)了該接口的List的具體實(shí)現(xiàn),使用for循環(huán)迭代的速度要遠(yuǎn)遠(yuǎn)高于Iterator循環(huán)。

As a rule of thumb, aList 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();

我們對(duì)ArrayList的for遍歷和Iteraotr的遍歷做一個(gè)簡(jiǎn)單測(cè)試,我們使用數(shù)據(jù)量為1000000的ArrayList,并遍歷10000次,并計(jì)算耗時(shí)。從計(jì)算結(jié)果看,當(dāng)數(shù)據(jù)量越大時(shí),for遍歷的時(shí)間優(yōu)勢(shì)越高。因此,我們?cè)谔幚泶髷?shù)據(jù)并要求高性能時(shí),這也是值得注意的一個(gè)點(diǎn)。

    public static long arrayFor() {
        List<Integer> list = new ArrayList<>();
        for (int i = 1; i <= 1000000; i++) {
            list.add(i);
        }
        
        long startTime = System.currentTimeMillis();

        for (int i = 0; i < 10000; i++) {
            for (int j = 0; j < list.size(); j++) {
                Object num = list.get(j);
            }
        }

        long endTime = System.currentTimeMillis();
        
        return endTime - startTime;
    }

    public static long arrayIterator() {
        List<Integer> list = new ArrayList<>();
        for (int i = 1; i <= 1000000; i++) {
            list.add(i);
        }
        
        long startTime = System.currentTimeMillis();

        for (int i = 0; i < 10000; i++) {
            Iterator iterator = list.iterator();
            while (iterator.hasNext()) {
                Object next = iterator.next();
            }
        }

        long endTime = System.currentTimeMillis();

        return endTime - startTime;
    }
    public static void main(String[] args) {
        long time1 = arrayFor();
        long time2 = arrayIterator();

        System.out.println("ArrayList for循環(huán)所用時(shí)間 = " + time1 + " ms");
        System.out.println("ArrayList 迭代器所用時(shí)間 = " + time2 + " ms");
    }

結(jié)果輸出:

ArrayList for循環(huán)所用時(shí)間 = 8 ms
ArrayList 迭代器所用時(shí)間 = 474 ms

Process finished with exit code 0

每日學(xué)習(xí)筆記,寫于2020-06-02 星期二

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容