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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…