Why would iterating over a List be faster than indexing through it?

后端 未结 5 1692
小蘑菇
小蘑菇 2020-12-12 11:38

Reading the Java documentation for the ADT List it says:

The List interface provides four methods for positional (indexed) access to list elements. Li

5条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-12 11:59

    In a linked list, each element has a pointer to the next element:

    head -> item1 -> item2 -> item3 -> etc.
    

    To access item3, you can see clearly that you need to walk from the head through every node until you reach item3, since you cannot jump directly.

    Thus, if I wanted to print the value of each element, if I write this:

    for(int i = 0; i < 4; i++) {
        System.out.println(list.get(i));
    }
    

    what happens is this:

    head -> print head
    head -> item1 -> print item1
    head -> item1 -> item2 -> print item2
    head -> item1 -> item2 -> item3 print item3
    

    This is horribly inefficient because every time you are indexing it restarts from the beginning of the list and goes through every item. This means that your complexity is effectively O(N^2) just to traverse the list!

    If instead I did this:

    for(String s: list) {
        System.out.println(s);
    }
    

    then what happens is this:

    head -> print head -> item1 -> print item1 -> item2 -> print item2 etc.
    

    all in a single traversal, which is O(N).

    Now, going to the other implementation of List which is ArrayList, that one is backed by a simple array. In that case both of the above traversals are equivalent, since an array is contiguous so it allows random jumps to arbitrary positions.

提交回复
热议问题