Do we ever need to use Iterators on ArrayList?

前端 未结 6 1414
南旧
南旧 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: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 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.

提交回复
热议问题