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

后端 未结 5 1701
小蘑菇
小蘑菇 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

    The answer is implied here:

    Note that these operations may execute in time proportional to the index value for some implementations (the LinkedList class, for example)

    A linked list doesn't have an inherent index; calling .get(x) will require the list implementation to find the first entry and call .next() x-1 times (for a O(n) or linear time access), where an array-backed list can just index into backingarray[x] in O(1) or constant time.

    If you look at the JavaDoc for LinkedList, you'll see the comment

    All of the operations perform as could be expected for a doubly-linked list. Operations that index into the list will traverse the list from the beginning or the end, whichever is closer to the specified index.

    whereas JavaDoc for ArrayList has the corresponding

    Resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list. (This class is roughly equivalent to Vector, except that it is unsynchronized.)

    The size, isEmpty, get, set, iterator, and listIterator operations run in constant time. The add operation runs in amortized constant time, that is, adding n elements requires O(n) time. All of the other operations run in linear time (roughly speaking). The constant factor is low compared to that for the LinkedList implementation.

    A related question titled "Big-O Summary for Java Collections Framework" has an answer pointing to this resource, "Java Collections JDK6" which you might find helpful.

提交回复
热议问题