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:
The code is much less readable with iterators.
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.
A big use case of iterators with ArrayLists is when you want to remove elements while iterating. You have only three safe solutions :
remove
methodAssuming 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.
None of the answers seem to adres the reason for iterators. The iterator design pattern was created because an object should be in control of its own state ( except maybe value objects with only public properties ).
Lets say we have an object that contains an array, and you have an interface in that object to add items to that array. But you have do something like this:
class MyClass
{
private ArrayList<Item> myList;
public MyClass()
{
myList = new ArrayList();
}
public addItem( Item item )
{
item.doSomething(); // Lets say that this is very important before adding the item to the array.
myList.add( item );
}
}
Now if i had this method in the class above:
public ArrayList getList()
{
return myList;
}
Somebody could get the reference to myList through this method and add items to the array, without calling item.doSomething(); That's why you shouldn't return a reference to the array, but instead return its iterator. One can get any item from the array, but it can't manipulate the original array. So the MyClass object is still in control of it's own state.
This is the real reason why iterators were invented.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With