在 Java 中使用迭代器有什么好处
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3595772/
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
What are the benefits of using an iterator in Java
提问by chronical
I was browsing over the following code example:
我正在浏览以下代码示例:
public class GenericTest {
public static void main (String[] args) {
ArrayList<String> myList = new ArrayList<String>();
String s1 = "one";
String s2 = "two";
String s3 = "three";
myList.add(s1); myList.add(s2); myList.add(s3);
String st;
Iterator<String> itr = myList.iterator();
while (itr.hasNext()) {
st = itr.next();
System.out.println(st);
}
}
}
I'm wondering what are the benefits of using an implementation of the Iterator interface instead of using a plain-old for-each loop?
我想知道使用 Iterator 接口的实现而不是使用普通的 for-each 循环有什么好处?
for ( String str : myList ) {
System.out.println(str);
}
If this example is not relevant, what would be a good situation when we should use the Iterator?
如果这个例子不相关,那么当我们应该使用 Iterator 时,什么是好的情况?
Thank you.
谢谢你。
采纳答案by Soundlink
The For-Each Loopwas introduced with Java 5, so it's not so "old".
该for-each循环与Java 5中引入的,所以它不是那么“老”。
If you only want to iterate a collection you should use the for each loop
如果你只想迭代一个集合,你应该使用 for each 循环
for (String str : myList) {
System.out.println(str);
}
But sometimes the hasNext()method of the "plain old" Iteratoris very useful to check if there are more elements for the iterator.
但有时hasNext()“普通旧”迭代器的方法对于检查迭代器是否有更多元素非常有用。
for (Iterator<String> it = myList.iterator(); it.hasNext(); ) {
String str = it.next();
System.out.print(str);
if (it.hasNext()) {
System.out.print(";");
}
}
You can also call it.remove()to remove the most recent element that was returned by next.
您还可以调用it.remove()删除 next 返回的最新元素。
And there is the ListIterator<E>which provides two-way traversal it.next()and it.previous().
还有ListIterator<E>提供双向遍历的it.next()和it.previous()。
So, they are not equivalent. Both are needed.
所以,它们并不等价。两者都需要。
回答by sinuhepop
Basically, foreach loop is a shortcut for the most common use of an iterator. This is, iterate through all elements. But there are some differences:
基本上,foreach 循环是迭代器最常见使用的快捷方式。也就是说,遍历所有元素。但也有一些区别:
- You can iterate through an array using foreach loop directly
- You can remove objects using an iterator, but you can't do it with a foreach loop
- Sometimes is useful to pass an iterator to a function (specially recursive ones)
- 您可以直接使用 foreach 循环遍历数组
- 您可以使用迭代器删除对象,但不能使用 foreach 循环来删除对象
- 有时将迭代器传递给函数很有用(特别是递归的)
回答by mhshams
for ( String str : myList ) { System.out.println(str); }
this code will actually use myList.Iterator to iterator over the list.
此代码实际上将使用 myList.Iterator 对列表进行迭代。
the new forloop added since java 5 to make iteration over the collections and arrays easier.
for自 java 5 以来添加的新循环使集合和数组的迭代更容易。
by Iterator each implementation in Java Collection can have its own way of iteration (List, Set, LinkedList, Map or ....)
通过 Iterator Java Collection 中的每个实现都可以有自己的迭代方式(List、Set、LinkedList、Map 或 ....)
you can implement this interface in your custom classes as well. to let other code iterator over the elements that you have inside your object.
您也可以在自定义类中实现此接口。让其他代码迭代器遍历您对象中的元素。
回答by YoK
I don't think there is any performance benefit in using either in most of cases if you are just iterating over collection/array. But usage may differ as per your use case.
如果您只是迭代集合/数组,我认为在大多数情况下使用这两种方法都没有任何性能优势。但是根据您的用例,用法可能会有所不同。
- If your case is only iteratingover list, use of for eachloop should be preffered since Java 1.5.
- But if your case is manipulatingcollection while iterating You need to use Iterator interface.
- 如果您的情况只是迭代列表, 那么从 Java 1.5 开始应该优先使用for 每个循环。
- 但是,如果您的情况在迭代时操作集合,则需要使用Iterator 接口。
回答by locka
An iterator is an abstraction over how a collection is implemented. It lets you go over the whole collection one item at a time, optionally removing items.
迭代器是对集合如何实现的抽象。它使您可以一次检查一个项目的整个集合,也可以选择删除项目。
The disadvantage of an Iterator is that it can be a lot slow if you DO know the underlying implementation. For example using an Iterator for an ArrayList is considerable slower than just calling ArrayList.get(i) for each element. Whether this matters much depends on what the code is doing.
Iterator 的缺点是,如果您知道底层实现,它可能会很慢。例如,对 ArrayList 使用 Iterator 比为每个元素调用 ArrayList.get(i) 慢得多。这是否重要取决于代码在做什么。
回答by samkass
The two are equivalent in operation and performance in almost all cases. The only difference is that Iterators are supported on old versions of the Java JVM while the new "for" syntax was only introduced in JSDK 1.5 ("Java 5"), and some folks want to remain compatible with 1.4 or earlier.
几乎在所有情况下,两者在操作和性能上都是等效的。唯一的区别是旧版本的 Java JVM 支持迭代器,而新的“for”语法仅在 JSDK 1.5(“Java 5”)中引入,有些人希望与 1.4 或更早版本保持兼容。

