【发布时间】:2013-04-06 16:30:46
【问题描述】:
我正在阅读问题中提到的答案 “Do we ever need to use Iterators on ArrayList?”。
在回答中,用户这样说:“使用 ArrayLists 的迭代器的一个重要用例是当您想要在迭代时删除元素”。
这甚至可以在 Java 中使用 ArrayList 的 remove 方法来实现。我的问题是为什么我们需要 ArrayList 中的迭代器?
考虑代码:
import java.util.*;
public class ocajp66 {
public static void main(String[] args) {
ArrayList a = new ArrayList();
for (int i = 0; i < 10; i++) {
a.add(i);
}
System.out.printf("BEFORE ITERATOR\n");
for (int i = 0; i < a.size(); i++) {
System.out.printf("I:%d\n", a.get(i));
}
System.out.printf("AFTER ITERATOR\n");
Iterator i = a.iterator();
while (i.hasNext()) {
System.out.printf("I:%d\n", i.next());
}
}
}
谁能解释一下迭代器的意义?如果你能用代码解释我,那就太好了。
【问题讨论】:
-
"在java中使用ArrayList的remove方法也可以实现。"你试过这个吗?
-
这个问题与链接的问题有何不同?
-
@Nambari 作为java初学者我想知道java中迭代器的意义为什么我们需要它当可以使用循环修改/删除/插入时
-
@Howard 在链接的问题中我无法理解迭代器的重要性。