为什么Iterator接口中没有add方法 [英] why there is no add method in Iterator interface

查看:167
本文介绍了为什么Iterator接口中没有add方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Iterator 中,Sun添加了remove方法来删除最后访问过的集合元素。为什么没有添加方法来向集合中添加新元素?它可能对集合或迭代器产生什么样的副作用?

解决方案

迭代器的唯一目的是枚举一个集合。所有集合都包含 add()方法,以满足您的需求。添加迭代器是没有意义的,因为可能会或可能不会订购该集合(在 HashSet 的情况下)。



编辑:在处理其他问题时,我想出了 Iterator 缺少的另一个原因add()方法。深入了解)?



总而言之,这样或那样的参数都有有效点,但底线是在所有情况下都没有很好地定义 add()方法的行为。 Sun必须选择限制功能的地方,并且他们选择不包含此方法。


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? What kind of side-effects it may have to the collection or iterator?

解决方案

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.

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.

这篇关于为什么Iterator接口中没有add方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆