java - Do we ever need to use Iterators on ArrayList? -
yesterday, when answering question getting concurrentmodificationexception error while using iterator , remove added notice that
it's not idea use iterators when have arraylists.
you not need understand question answer on one.
there, got 2 comments i'm wrong.
my arguments:
the code less readable iterators.
there possibility raise concurrentmodificationexception hard debug.
can please explain?
question: ever need use iterators on arraylist?
upd
this explicitly using iterator.
a big use case of iterators arraylists when want remove elements while iterating. have 3 safe solutions :
- use iterator ,
remove
method - copy elements want keep in list
- jungle indexes
assuming don't add
while iterating, using iterator mean avoid concurrentmodificationexception
.
the readability argument subjective. don't find cleanly declared iterator less readable. , doesn't matter iterator safe way iterate , remove @ same time.
Comments
Post a Comment