我们是否需要在ArrayList上使用迭代器? [英] Do we ever need to use Iterators on ArrayList?

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

问题描述

昨天,当我回答问题使用迭代器并删除时出现ConcurrentModificationException错误我添加了一条通知

Yesterday, when I was answering to question getting ConcurrentModificationException error while using iterator and remove I added a notice that


当你有ArrayLists时使用迭代器不是一个好主意。

It's not a good idea to use iterators when you have ArrayLists.

你不需要深刻理解那个问题就可以回答。

You do not need to deeply understand that question to answer on that one.

在那里,我得到两条评论,我错了。

There, I got two comments that I'm wrong.

我的论点:


  1. 迭代器的代码可读性差得多。

  1. The code is much less readable with iterators.

有可能引发难以调试的ConcurrentModificationException。

There is a possibility to raise ConcurrentModificationException that is hard to debug.

你能解释一下吗?

问题:
我们是否需要在ArrayList上使用Iterators?

Question: Do we ever need to use Iterators on ArrayList?

UPD

这是关于明确使用Iterator。

This is about explicitly using Iterator.

推荐答案

很有用使用ArrayLists的迭代器的情况是在迭代时要删除元素的时候。您只有三个安全的解决方案:

A big use case of iterators with ArrayLists is when you want to remove elements while iterating. You have only three safe solutions :


  • 使用迭代器及其删除方法

  • 将要保留的元素复制到另一个列表中

  • 带索引的丛林

  • use an iterator and its remove method
  • copy the elements you want to keep in another list
  • jungle with indexes

假设你在迭代时没有添加,使用迭代器是避免 ConcurrentModificationException 。

Assuming you don't add while iterating, using the iterator is a mean to avoid the ConcurrentModificationException.

可读性参数是主观的。我个人认为没有一个干净的声明迭代器可读性较差。并且它并不重要,因为迭代器是同时迭代和删除的安全方式。

The readability argument is subjective. Personally I don't find a cleanly declared iterator less readable. And it doesn't really matter as the iterator is the safe way to iterate and remove at the same time.

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

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