Confirm the Java LinkedList “foreach” loop

nice day,

Someone can confirm the content at the bottom of the Java – iterating a linked list post. The post mentioned that you can use the for (char c: linked list of chars) syntax, which is still o (n) I want to access a list that looks like this

a b c d e f

In fact, it runs at the beginning of the linked list during each iteration of the for loop, like this

a ab abc abcde abcdef

The access time is not o (n)

How does this work? It makes sense for arrays and array operators, but how does Java syntax know how to use the foreach loop in Java to traverse the linked list?

I think the LinkedList data structure is just an additional library, not part of the core language syntax (I do know that the LinkedList class is standard in Java.)

I hope I can clearly explain my concerns thank you

Solution

First, an instance of any class that implements Iterable can be used in a foreach loop The reason is that after compilation, for (Suite: Suite) actually becomes (iterator I = suit. Iterator(); i.hasNext();). For details, see this explanation

Sets implement optimized iterators specific to data structures Specifically for LinkedList, the iterator maintains a pointer to the last returned object to allow constant time next () and previous () operations Therefore, using foreach loop to iterate the linked list will lead to o (n) time complexity You can view the source code for more details

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>