How enhanced is enhanced-for loop?

寵の児 提交于 2019-12-30 11:09:07

问题


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.


回答1:


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.




回答2:


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);
}

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




回答3:


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




回答4:


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.



来源:https://stackoverflow.com/questions/24274124/how-enhanced-is-enhanced-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!