Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
197 views
in Technique[技术] by (71.8m points)

java - Do we ever need to use Iterators on ArrayList?

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

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.

My arguments:

  1. The code is much less readable with iterators.

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

Can you please explain?

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

UPD

This is about explicitly using Iterator.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...