Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we ever need to use Iterators on ArrayList?

Tags:

java

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.

like image 808
Vitaly Avatar asked Apr 05 '13 06:04

Vitaly


2 Answers

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.

like image 197
Denys Séguret Avatar answered Oct 07 '22 23:10

Denys Séguret


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.

like image 23
David Avatar answered Oct 07 '22 22:10

David