我在 Goodrich 的《数据结构和算法》中读到了以下内容:
Java 通过其 java.util.Iterator 接口提供迭代器。我们
请注意,java.util.Scanner 类(第 1.6 节)实现了此功能
界面。该接口支持附加(可选)方法
从集合中删除先前返回的元素。这
功能(通过迭代器删除元素)有点
然而,从面向对象的角度来看,这是有争议的
毫不奇怪,它的类实现是可选的
我不明白作者在这里指的是什么。这里讨论的是哪种方法,它有什么作用?
I read the following in Data Structures and Algorithms by Goodrich :
Java provides an iterator through its java.util.Iterator interface. We
note that the java.util.Scanner class (Section 1.6) implements this
interface. This interface supports an additional (optional) method to
remove the previously returned element from the collection. This
functionality (removing elements through an iterator) is somewhat
controversial from an object-oriented viewpoint, however, and it is
not surprising that its implementation by classes is optional
I don't understand what the author is referring to here. Which is the method in discussion here and what does it do?
发布评论
评论(6)
可能是 Iterator.remove() 方法。
Probably the Iterator.remove() method.
有问题的方法是 Iterator.remove() ,它是 迭代器接口。
许多 Iterator 实例不支持它 - 如果您尝试在错误类型的迭代器上调用它,您很可能会得到 UnsupportedOperationException。
我个人认为,作为 Iterator 接口的一部分,remove() 并不是一个好主意:Iterator 的主要概念目的是单次遍历集合的元素并按顺序返回这些元素。
如果您遵循“做好一件事”的设计学派,那么尝试使用迭代器作为修改此类集合的技术是一个坏主意。从并发角度来看,这种行为也会引起很大的麻烦......
The method in question is Iterator.remove() which is part of the Iterator interface.
A lot of Iterator instances don't support it - if you try to call it on the wrong kind of iterator you will most likely get an UnsupportedOperationException.
I personally don't think remove() is a very good idea as part of the Iterator interface: the primary conceptual purpose of an Iterator is to do a single pass through the elements of a collection and return these elements in sequence.
If you follow the "do one thing well" school of design, then it's a bad idea to also try to use Iterators as a technique for modifying such collections. Such behaviour can also cause big headaches from a concurrency perspective....
remove() 方法是可选的,它从 Collection 中删除 next() 返回的最后一个元素。
The remove() method is optional and removes the last element returned by next() from the Collection.
remove()
方法将删除最近从next()
返回的元素。The
remove()
method will delete the element that was most recently returned fromnext()
.Iterator.remove(),它删除调用 next() 或 previous() (如果是 ListIterator)
Iterator.remove(), which removes the last node returned by a call of next() or previous() (if it is a ListIterator)
在 迭代器接口,有一个
remove()
函数可以选择性地实现。文件说:基本上,它进入迭代器生成的集合,并从原始集合中删除当前迭代中的元素。
In the Iterator Interface, there is an
remove()
function which can be optionally implemented. The Docs say:Basically it goes into the collection from where the iterator was spawned and removes the element in the current iteration from the original collection.