如何增强for-loop? [英] How enhanced is enhanced-for loop?

查看:127
本文介绍了如何增强for-loop?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在一个接一个地迭代String对象列表的元素

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

这里,每次我在列表上调用get()时,列表都会从列表中重复它的结尾一直到第i个元素 - 所以上面循环的复杂性是O(n ^ 2)。

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).

是a。)相同如上所述,对于增强型for循环,或b。)是for循环保持指针的最后位置,因此下面循环的复杂性是O(n)?

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

如果上面的情况(b) - 我认为是 - 那么在列表中使用迭代器的优点。这是一个简单的迭代 - 没有回头和前后。编辑:..我的列表操作是只读的。

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. ..and my list operation is read-only.

TIA。

推荐答案

你称之为增强的for循环(它实际上叫做 foreach loop)在内部使用迭代器来处理任何迭代 - 包括链表。

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.

换句话说它是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.

这篇关于如何增强for-loop?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆