Do we ever need to use Iterators on ArrayList?

前端 未结 6 1405
南旧
南旧 2020-12-13 22:00

Yesterday, when I was answering to question getting ConcurrentModificationException error while using iterator and remove I added a notice that

It\'s

相关标签:
6条回答
  • 2020-12-13 22:20

    The code is much less readable with iterators.

    That's entirely your opinion, and I don't share it.

    There is a possibility to raise ConcurrentModificationException that is hard to debug.

    That possibly exists whether you use Iterators or not. That exception tells you something useful about your code that you might otherwise miss altogether, which is even harder to debug.

    Personally I prefer being able to write exactly the code as between ArrayList and LinkedList, and having the compiler or the API implement the details.

    The moral is that you shouldn't pass off your own unsupported opinion as established fact.

    0 讨论(0)
  • 2020-12-13 22:21

    Yes, we need. ArrayList is just an implementation of the List interface, so often your code will process a list and not even know that it's an ArrayList. Also, the new for-loop syntax uses iterators internally.

    0 讨论(0)
  • 2020-12-13 22:35

    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.

    0 讨论(0)
  • 2020-12-13 22:38

    You are probably talking about explicitly using an iterator (since the : operator is also using the iterator behind the scenes).

    Say you want to have two "pointers" going over the array but the speed depends on the actual element values. How would you do this without explicitly using iterators (and without elementAt of course).

    For example (pseudo code):

    element1 = first element;
    element2 = first element;
    while(element1.hasNext && element2.hasNext)
    {
        if(element1 * 2 < element)
        {
            element2 = element2.next;
        }
        else
        {
            element1 = element1.next;
        }
    
        //do something with the pair of elements
    }
    
    0 讨论(0)
  • 2020-12-13 22:39

    Check this post: http://www.xyzws.com/javafaq/what-is-the-advantage-of-using-an-iterator-compared-to-the-getindex-method/19

    Using iterator will avoid the mistake of using get(index) on LinkedList(extremely slow). It makes sense when the implementation of list is unknown, just use iterator. Regarding ArrayList, using iterator will still achieve the closest possible performance with get(index).

    So it is a good practice to use iterator for iterating in terms of performance.

    0 讨论(0)
  • 2020-12-13 22:40

    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.

    0 讨论(0)
提交回复
热议问题