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

查看:32
本文介绍了为什么我们需要在 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\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());
        }
    }
}

谁能解释一下迭代器的意义?要是能用代码解释一下就好了.

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天全站免登陆