为什么使用“迭代器”遍历ArrayList。没有迭代器也可以完成吗? 因此使用迭代器遍历ArrayList的好处
import java.util.ArrayList;
import java.util.Iterator;
public class IteratorDemo {
public static void main(String[] args) {
// Make a collection
ArrayList<String> cars = new ArrayList<String>();
cars.add("Volvo");
cars.add("BMW");
cars.add("Ford");
cars.add("Mazda");
// Get the iterator
//Iterator<String> it = cars.iterator();
// Looping without Iterator
for(int i=0;i<4;i++) {
//System.out.println(it.next());
System.out.println(cars.get(i));
}
}
}
答案 0 :(得分:2)
有时您只是不需要索引,因此更容易。但是,尝试使用索引的for循环执行此操作。可以做到,但不那么容易。
List<Integer> list = new ArrayList<>(
List.of(1, 2, 2, 3, 4, 4, 5, 6, 6, 7, 8, 8, 9, 10, 10));
Iterator<Integer> it = list.iterator();
while (it.hasNext()) {
// if even, remove it.
if (it.next() % 2 == 0) {
it.remove();
}
}
System.out.println(list);
打印
[1, 3, 5, 7, 9]
使用interator
可让您修改可能会触发并发修改异常的列表。
此外,假设您有一个生成素数或斐波那契数的类实现。您可以这样做来单独抓住它们。
Fibonacci fib = new Fibonacci(0, 1, 10);
for (long i : fib) {
System.out.print(i + " ");
}
打印
0 1 1 2 3 5 8 13 21 34
斐波那契类
class Fibonacci implements Iterable<Long> {
public long start;
public long next;
public long count;
public Fibonacci(int start, int next, int count) {
this.start = start;
this.next = next;
this.count = count;
}
private class MyIterator implements Iterator<Long> {
int n = 0;
public boolean hasNext() {
return n < count;
}
public Long next() {
n++;
long ret = start;
start = start + next;
next = ret;
return ret;
}
}
public Iterator<Long> iterator() {
return new MyIterator();
}
}
通过在类中实现Iterable
,我可以使用foreach
构造获取类的元素。
答案 1 :(得分:0)
您可能没有直接使用它的好处。但是,例如forEach使用了迭代器。
答案 2 :(得分:0)
只需遍历它就不需要迭代器,for循环就足够了。如果需要修改列表,则需要避免ConcurrentModificationException。