为什么我们需要在 Java 中的 ArrayList 上使用迭代器? [英] Why do we need to use iterator on ArrayList in Java?

查看:30
本文介绍了为什么我们需要在 Java 中的 ArrayList 上使用迭代器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读问题中提到的答案"我们是否需要在 ArrayList 上使用迭代器?".

I was reading the answer mentioned to the question "Do we ever need to use Iterators on ArrayList?".

在回答中,用户这样说:使用 ArrayLists 的迭代器的一个重要用例是当您想要在迭代时删除元素".

In the answer, the user stated something like this: "A big use case of iterators with ArrayLists is when you want to remove elements while iterating".

这甚至可以在 Java 中使用 ArrayList 的 remove 方法来实现.我的问题是为什么我们需要 ArrayList 中的迭代器?

This could be achieved even using remove method of ArrayList in Java. My question is why we need iterator in 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
");
        for (int i = 0; i < a.size(); i++) {
            System.out.printf("I:%d
", a.get(i));
        }
        System.out.printf("AFTER ITERATOR
");
        Iterator i = a.iterator();
        while (i.hasNext()) {
            System.out.printf("I:%d
", i.next());
        }
    }
}

谁能解释一下迭代器的意义?如果你能用代码解释我,那就太好了.

Can anybody explain the significance of the iterator? It would be wonderful if you could explain me with code.

推荐答案

正如您所说,当您想要在迭代数组内容时删除内容时使用迭代器.如果您不使用迭代器,而只是有一个 for 循环并在其中使用 remove 方法,您将得到异常,因为在您迭代时数组的内容会发生变化.例如:你可能认为在 for 循环开始时数组大小是 10,但一旦你删除东西就不会这样了.所以当你到达最后一个循环时,可能会有 IndexOutofBoundsException 等.

As you have stated iterator is used when you want to remove stuff whilst you iterate over the array contents. If you don't use an iterator but simply have a for loop and inside it use the remove method you will get exceptions because the contents of the array changes while you iterate through. e.g: you might think array size is 10 at the start of the for loop but it wont be the case once you remove stuff.. so when u reach the last loops probably there will be IndexOutofBoundsException etc.

这篇关于为什么我们需要在 Java 中的 ArrayList 上使用迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆