为什么我们需要在 Java 中的 ArrayList 上使用迭代器

Why do we need to use iterator on ArrayList in Java?(为什么我们需要在 Java 中的 ArrayList 上使用迭代器?)
本文介绍了为什么我们需要在 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 上使用迭代器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

【网站声明】本站部分内容来源于互联网,旨在帮助大家更快的解决问题,如果有图片或者内容侵犯了您的权益,请联系我们删除处理,感谢您的支持!

相关文档推荐

Java Remove Duplicates from an Array?(Java从数组中删除重复项?)
How to fix Invocation failed Unexpected Response from Server: Unauthorized in Android studio(如何修复调用失败来自服务器的意外响应:在 Android 工作室中未经授权)
AES encryption, got extra trash characters in decrypted file(AES 加密,解密文件中有多余的垃圾字符)
AES Error: Given final block not properly padded(AES 错误:给定的最终块未正确填充)
Detecting incorrect key using AES/GCM in JAVA(在 JAVA 中使用 AES/GCM 检测不正确的密钥)
AES-256-CBC in Java(Java 中的 AES-256-CBC)