Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...