Monday, September 8

Why Iterator interface provides remove() method but no add() method?

The Interface Iterator provider as three method that are hasNext(), next() and remove(). 
This means that we can remove any element from a collection while iterating over it. so why we cannot add element to the collection. Why they don't provide add() method.

Answer is, that they can't allow you to concurrently read and add element to a collection. The Iterator work on any collection whether it Set, List or Map. So it does know very much the on which underlying it's going to work and we know all the collection implementation maintain ordering of elements based on some algorithm. For example  TreeSet maintains the order of elements in by implementation Red-Black Tree data structure. Therefore if we tried to add an element to TreeSet using the iterator at given index or position of iterator. it might corrupt the state of the underlying data structure. So, the add()method could change structural state of a data structure. 

Ads Inside Post