java 迭代器与 for 循环以及为什么像我们有 for 循环一样引入迭代器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5504570/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
iterator vs for loop and why iterator was introduced as we had for loop?
提问by user686303
Possible Duplicates:
What are the Advantages of Enhanced for loop and Iterator in Java ?
Is there a performance difference between a for loop and a for-each loop?
可能的重复:
Java 中增强的 for 循环和迭代器的优点是什么?
for 循环和 for-each 循环之间是否存在性能差异?
Below code shows that with both for loop as well as with iterator we can iterate the elements of collection then what is the difference between for loop and iterator and why we should use only iterator in case of collection
下面的代码显示,使用 for 循环和迭代器我们都可以迭代集合的元素,那么 for 循环和迭代器之间的区别是什么以及为什么我们应该在集合的情况下只使用迭代器
ArrayList<String> list=new ArrayList<String>();
list.add("dipu");
list.add("alok");
list.add("alok");
list.add("jyoti");
ArrayList<Integer> al=new ArrayList<Integer>();
al.add(1);
al.add(2);
String a[]={"a","b"};
for(int i=0;i<list.size();i++)
{
System.out.println(list.get(i));;
}
for(Integer t:al)
{
System.out.println(t);
}
for (Iterator iter = list.iterator(); iter.hasNext();)
{
System.out.println(iter.next());
}
Iterator it=list.iterator();
while(it.hasNext())
{
String st=it.next().toString();
System.out.println(st);
}
回答by KeithS
Though I'm not familiar with the Java Iterator, it seems very similar to .NET's IEnumerable.
虽然我不熟悉 Java Iterator,但它似乎与 .NET 的 IEnumerable 非常相似。
The advantages of the enumerator/iterator are:
枚举器/迭代器的优点是:
You don't have to know the size of the collection, which in some cases can require N steps to determine, increasing execution time (though it remains technically linear). Instead, you just keep moving to the next element until there aren't any.
Because the cardinality of the collection doesn't have to be known, iterators can allow collections to be generated dynamically, or "streamed" with elements being added while you begin work on what you already have. For instance, you could derive from Iterator and/or overload iterator getters to create classes that generate finite or infinite series "lazily", figuring out what each element in your enumerable collection is when you ask for it instead of when you define the collection. You could also set up a buffered stream, where you process records, packets, etc that you have received, while another thread or process works ahead of you to queue up more for you to work on.
Any collection that can provide an iterator can be traversed in exactly the same way, instead of having to know whether it's indexable, what the method or member is that defines size, etc etc etc. Iterator implementations thus provide an adapter to allow the same code to work on any collection passed to it.
Does Java have an equivalent to .NET extension methods (static methods that are not part of the class definition, but that work on instances of the type and can be called as if they were instance methods)? If so, you can define methods that take an Iterator and produce a result, which could be another Iterator. .NET's Linq library is based heavily on these, providing a very powerful collection-manipulation framework allowing for common operations to be chained together, each operating on the result of the previous operation.
您不必知道集合的大小,在某些情况下可能需要 N 步来确定,从而增加了执行时间(尽管它在技术上保持线性)。相反,您只需继续移动到下一个元素,直到没有任何元素。
因为不必知道集合的基数,迭代器可以允许动态生成集合,或者在您开始处理已有的内容时“流式传输”添加的元素。例如,您可以从 Iterator 和/或重载迭代器 getter 派生以创建“懒惰地”生成有限或无限系列的类,找出可枚举集合中的每个元素在您请求时而不是在定义集合时是什么。您还可以设置一个缓冲流,在其中处理您收到的记录、数据包等,而另一个线程或进程在您之前工作以排队更多供您处理。
可以以完全相同的方式遍历任何可以提供迭代器的集合,而不必知道它是否可索引、定义大小的方法或成员是什么等等。因此,迭代器实现提供了一个适配器以允许相同的代码处理传递给它的任何集合。
Java 是否具有与 .NET 扩展方法等效的方法(不属于类定义的静态方法,但适用于该类型的实例并且可以像实例方法一样调用它们)?如果是这样,您可以定义采用 Iterator 并产生结果的方法,该结果可能是另一个 Iterator。.NET 的 Linq 库在很大程度上基于这些,提供了一个非常强大的集合操作框架,允许将常见操作链接在一起,每个操作都对前一个操作的结果进行操作。
回答by Prine
I try to explain it with two short sentences:
我试着用两句话来解释:
- With the enhanced for loopits easier to loop over it (more human readable..)
- With the iteratorsit is possible to modify the list during the iteration, which is with the other methods not possible
- 使用增强的 for 循环可以更容易地循环它(更易读..)
- 使用迭代器可以在迭代期间修改列表,这是其他方法不可能的
回答by gnomed
Iterators are just generally safer I would say, no risk of accessing an index that isn't there. They also have a little more flexibility since you can go backwards and forwards with them whereas for loops only go one way and in many languages you cannot alter the value of the loop index within the loop (i.e. you cannot change the increment rate).
我想说的是,迭代器通常更安全,没有访问不存在的索引的风险。它们还具有更大的灵活性,因为您可以使用它们前后移动,而 for 循环只能采用一种方式,并且在许多语言中,您无法更改循环内循环索引的值(即,您无法更改增量速率)。
They are also the ONLY way to remove items from a collection while iterating through them. Removing an item from a collection while you were in a for loop through it would be disastrous and is generally not even allowed by Java, I forget what the exception is, but I've got one for doing that before.
它们也是在迭代时从集合中删除项目的唯一方法。在 for 循环中从集合中删除项目将是灾难性的,Java 通常甚至不允许,我忘记了例外是什么,但我以前有一个这样做的。
Think about it, once you remove the item all the other ones shift down. Meanwhile on your next iteration your index was still incremented meaning 2 things.
想一想,一旦您删除了该项目,所有其他项目都会向下移动。同时,在您的下一次迭代中,您的索引仍会增加,这意味着两件事。
First is that you will skip whatever the next element is as it was shifted to the position you just deleted from.
首先是你将跳过下一个元素,因为它被转移到你刚刚删除的位置。
Second is that your loop will extend beyond the size of the collection which you have now altered.
其次,您的循环将超出您现在更改的集合的大小。
回答by n8wrl
The 'stream' you're iterating on might not even be indexable. That is, the iterator makes possible a very convenient 'lazy-evaluation' pattern where data isn't even loaded/constructed until the iterator asks for it. This is wonderful for repositories and database access, as well as networking.
您正在迭代的“流”甚至可能无法编入索引。也就是说,迭代器使一种非常方便的“懒惰评估”模式成为可能,在该模式中,在迭代器要求之前甚至不会加载/构造数据。这对于存储库和数据库访问以及网络非常有用。