在Java中使用迭代器有什么好处 [英] What are the benefits of using an iterator in Java
问题描述
我正在浏览以下代码示例:
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);
}
}
}
我想知道什么是使用Iterator接口的实现而不是使用普通的for-each循环的好处?
I'm wondering what are the benefits of using an implementation of the Iterator interface instead of using a plain-old for-each loop?
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?
谢谢。
推荐答案
For-Each循环是在Java 5中引入的,所以它不是那么老。
The For-Each Loop was introduced with Java 5, so it's not so "old".
如果你只想迭代一个集合,你应该使用for each循环
If you only want to iterate a collection you should use the for each loop
for (String str : myList) {
System.out.println(str);
}
但有时 hasNext()
普通旧迭代器的方法对于检查迭代器是否有更多元素非常有用。
But sometimes the hasNext()
method of the "plain old" Iterator is very useful to check if there are more elements for the iterator.
for (Iterator<String> it = myList.iterator(); it.hasNext(); ) {
String str = it.next();
System.out.print(str);
if (it.hasNext()) {
System.out.print(";");
}
}
您也可以拨打它.remove()
删除next返回的最新元素。
You can also call it.remove()
to remove the most recent element that was returned by next.
还有 ListIterator< E>
,它提供双向遍历。 next()
和 it.previous()
。
And there is the ListIterator<E>
which provides two-way traversal it.next()
and it.previous()
.
所以,它们并不等同。两者都是必需的。
So, they are not equivalent. Both are needed.
这篇关于在Java中使用迭代器有什么好处的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!