java 資料結構. 源碼閱讀__資料結構

來源:互聯網
上載者:User




Collections工具類裡的


Collections.synchronizedList


public static <T> List<T> synchronizedList(List<T> list) {
    return (list instanceof RandomAccess ?
                new SynchronizedRandomAccessList<T>(list) :
                new SynchronizedList<T>(list));
    }

##僅僅是通過判斷是否實現RandomAccess介面,而返回不同的SynchronizedList(內部)類,

##RandomAccess foreach較快, iterator較慢,差別不明顯(如i5上,本人測試,一個ArrayList,90w個object,  foreach出來是6多ms, iterator出來7ms)

##SequenceAccess foreach較慢,iterator較快.差別非常明顯. (如i5上,本人測試,一個LinkedList,10w個object,  foreach出來是200多ms, iterator出來僅4ms)



LinkedList的get(n) 方法.   源碼裡寫得也有點妙,一不留意 確實是個坑.    (這是SequenceAccess 的foreach 慢的原因)

private Entry<E> entry(int index) {
        if (index < 0 || index >= size)
            throw new IndexOutOfBoundsException("Index: "+index+
                                                ", Size: "+size);
        Entry<E> e = header;
        if (index < (size >> 1)) {
            for (int i = 0; i <= index; i++)
                e = e.next;
        } else {
            for (int i = size; i > index; i--)
                e = e.previous;
        }
        return e;
    }






聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.