為什么LinkedList不建議使用for循環遍歷,而使用iterator方式進行遍歷,但ArrayList建議使用for循環進行遍歷呢?


如果使用for循環方式遍歷鏈表,由於鏈表中元素是通過指針連接彼此的,不存在索引的概念,如果使用for循環方式遍歷LinkedList,依次傳入索引值,則就相當於每次都要將鏈表擼一遍。

如:在下面的這個遍歷操作中,我們采用for的方式

public static void main(String[] args)
{
    List<Integer> linkedList = new LinkedList<Integer>();
    
    for (int i = 0; i < 100; i++)
    {
        linkedList.add(i);
    }
    for (int i = 0; i < 100; i++)
    {
        System.out.println(linkedList.get(i));
    }
} 

實際上底層所執行的操作是,拿到這個值:

     public E get(int index) {
        checkElementIndex(index);
        return node(index).item;
     }
     /**
     * Returns the (non-null) Node at the specified element index.
     */
    Node<E> node(int index) {
        // assert isElementIndex(index);
         
        if (index < (size >> 1)) {
            Node<E> x = first;
            //遍歷鏈表,找到下標所對應的節點
            for (int i = 0; i < index; i++)
                x = x.next;
            return x;
        } else {
            Node<E> x = last;
            for (int i = size - 1; i > index; i--)
                x = x.prev;
            return x;
        }
    }

​ 可以發現,如果使用for循環方式遍歷LinkedList,問題的焦點是每次get()方法接收一個值,都會對鏈表遍歷找到這個數值在鏈表中所對應的節點,肯定效率不高,而如果是ArrayList,由於它底層使用的對象數組實現,對象數組能夠支持隨機訪問,所以效率比較高。

​ 那為什么使用iterator方式來遍歷LinkedList效率比較高呢?這是因為iterator的next(),是順着鏈表節點順序讀取數據,所以效率就很高了。

​ 究其根本原因是數組支持隨機訪問,但是鏈表不支持隨機訪問。

參考鏈接1:https://blog.csdn.net/OrPis/article/details/80839303

參考鏈接2:https://blog.csdn.net/qq_36520235/article/details/82535044


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM