The Interface Iterator provider as three method that are
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
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.
remove() method doesn’t change or violate any state and rule of data structure or of the algorithm.
ListIterator provide the
add() methods because it know the location where it needs to add the newly created element as List preserves the order of its element in order of their insertion.
Please do comment…Share :
Subscribe to this blog via RSS.