为什么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

原文地址:https://www.cnblogs.com/cosmos-wong/p/11931275.html