why there is no add method in Iterator interface

前端 未结 6 1599
逝去的感伤
逝去的感伤 2021-02-01 06:05

In Iterator Sun added the remove method to remove the last accessed element of the collection. Why there is no add method to add a new element to the collection? Wh

6条回答
  •  清酒与你
    2021-02-01 06:51

    The sole purpose of an Iterator is to enumerate through a collection. All collections contain the add() method to serve your purpose. There would be no point in adding to an Iterator because the collection may or may not be ordered (in the case of a HashSet).

    EDIT: While working on another problem, I came up with another reason that Iterator lacks an add() method. Looking under the hood of ArrayList (line 111), and HashMap (line 149), we see that the implementation is just a few methods surrounding an array of objects. Now we consider how arrays are treated in memory.

    zero-based array indexes

    This is an array of 5 elements. However, there are six indices. The letter "a" in this array is listed as element 0 because in order to read it, left to right like a computer does, you have to start at index 0. Now, if we are iterating through this array (yes, collection, but it boils down to an array), we will start at index 0 and continue to index 1. At this point in the Iterator, we want to call add("f");. At this point, let's compare the implications of add() and remove(). remove() would leave a space in the array, which is easy to jump over, because we can immediately recognize that it isn't a member. On the other hand, add() would put a new element in which wasn't there before. This will affect the length of the array that we're iterating through. What happens when we get to that last element? Can we even guarantee that it is there (that is, that the array hasn't exceeded the maximum size)?

    All in all, the arguments one way or another both have valid points, but the bottom line is that the behavior of an add() method is not well defined in all cases. Sun had to make a choice where to limit functionality, and they chose not to include this method.

提交回复
热议问题