开发者

why iterator.remove() has been described as optional operation?

I went through the documentation(http://java.sun.com/javase/6/docs/api/java/util/Iterator.html) of Iterator.remove() there remove() was described as

void remove()

开发者_如何学GoRemoves from the underlying collection the last element returned by the iterator (optional operation). This method can be called only once per call to next. The behavior of an iterator is unspecified if the underlying collection is modified while the iteration is in progress in any way other than by calling this method.

  1. So can anybody tell what "optional" means.
  2. Does this affect the robustness of operation?(Like c++ ,it does not guarantee the robustness of the operations.)
  3. Why "optional" has been specified categorically here.
  4. What does "modification" mean in the second line of documentation

behavior of an iterator is unspecified if the underlying collection is modified


#1: Optional means you can implement it or throw an UnsupportedOperationException

#2: This operation is optional because sometimes you just don't want your iterator's content to be modified. Or what do you understand by "robustness of operation"?

EDIT #4: behavior of an iterator is unspecified if the underlying collection is modified

Normally, you use an iterator by executing

List<String> c = new ArrayList<String>();
c.add("Item 1");
c.add("Item 2");
c.add("Item 3");
...
for (Iterator<String> i = c.iterator(); i.hasNext();)
{
  String s = i.next();
  ...
}

If you now would want to remove an item while iterating through the list, and you would call

c.remove("Item 2");

this is not clean, possibly corrupts data in your List/Collection/... and should be avoided. Instead, remove() the item through the iterator:

i.remove();


First of all java.util.Iterator is an interface i.e. an agreement how classes that implement this interface interract with the rest of the world. It's their responsibility how they'll implement interaface's methods.

If the underlying data structure doesn't allow removal then remove() will throw an UnsupportedOperationException. For example, if you are iterating through a result set retrieved from a DB it does make sense not to implement this method.

If you iterate over some collection which is shared between concurrent threads and the other thread modifies the data iterating thread then will return undeterministic results.


It is described as being optional because not all collection classes that can give you an iterator implement the remove() method in the iterator they return. If the returned iterator doesn't implement it, an UnsupportedOperationException will be thrown.

The normal java.util.ArrayList, java.util.LinkedList and other standard collection classes all implement the remove() method in their iterators, so you can use it safely.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜