简体   繁体   中英

How enhanced is enhanced-for loop?

I am iterating on the elements of a list of String objects one after the other:

LinkedList list;

// add values to the list here


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

Here, each and every time i invoke get() on list, the list is iterated from one of its ends all the way to the i-th element-- so the complexity of the above loop is O(n^2).

Is is a.) the same as above for enhanced-for loop, or b.) is for-loop maintaining the pointer where it's last have been and thus the complexity of the below loop is O(n)?

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

If case (b) above -- which i think it is -- is there any advantage of using an iterator on the list. this is plain iteration-- there's no going back&forth. EDIT: ..and my list operation is read-only.

TIA.

The "enhanced for loop" as you call it (it's actually called the foreach loop) internally uses an iterator for any iterable - including linked lists.

In other words it is O(n)

It does handle looping over arrays by using an integer and iterating over it that way but that's fine as it performs well in an array.

The only advantages of using an iterator manually are if you need to remove some or all of the elements as you iterate.

A foreach loop like this:

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

Would be desugared to something like

for(Iterator<String> iter = list.iterator(); iter.hasNext();) {
    String s = iter.next();
    System.out.println(s);
}

ie it is equivalent to using an Iterator . And much better than using a standard for loop.

Enhanced loop uses an Iterator behind the scenes [ 1 ] if it is about lists.

In your case you have a linked list (which keeps pointers to next-previous items), so by using an enhanced for (iterator) you have sequential read complexity O(1) .

If you use the for you suggested, you're accessing your list randomly, which is O(n) for the LinkedList but it would be O(1) if it was an ArrayList.

So it can be enhanced if used in a List with sequential read complexity < random read complexity

[1] why is enhanced for loop efficient than normal for loop

Enhanced for loop is useful in certain situations like when there is a need to search a key in an array,where it obtains one element at a time in sequence. It eliminates the need to establish loop counter,specify starting and ending value.So based on the requirement simple for loop or enhanced for loop can be used.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM