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

Categories

0 votes
182 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 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...