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

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

问题描述

我在读提到这个问题的答案
我们曾经需要在ArrayList的使用迭代器?

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

在答案中,用户表示是这样的:用的ArrayList迭代器的一大用例是当你想删除元素,而迭代

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".

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

This could be achieved even using remove method of ArrayList in Java. My question is why we need iterator in ArrayList?

考虑code:

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());
        }
    }
}

谁能解释迭代器的意义何在?这将是美好的,如果你能以code解释我。

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

推荐答案

正如你们所指出的迭代器是用来当你想,而你遍历数组内容去掉的东西。如果不使用迭代器,而只是有一个for循环和里面使用remove方法,因为数组的内容发生变化,而你遍历你会得到异常。例如:你可能会认为数组大小是10日在for循环的开始,但它不会是,一旦你删除的东西..所以当u到达最后的循环可能会出现的情况下抛出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天全站免登陆