为什么iterator.remove()被描述为可选操作? [英] why iterator.remove() has been described as optional operation?

查看:147
本文介绍了为什么iterator.remove()被描述为可选操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我浏览了文档( http:/ /java.sun.com/javase/6/docs/api/java/util/Iterator.html Iterator.remove()
remove()被描述为

  void remove()



从底层集合中删除迭代器返回
的最后一个元素(可选操作)。
这个方法只能调用一次

迭代器的行为是未指定的,如果
底层集合被修改
,而迭代正在以
方式进行,而不是通过调用此
方法。 / p>




  1. 任何人都可以告诉可选是什么意思。

  2. 这是否会影响操作的鲁棒性?(像c ++一样,它不能保证操作的稳健性。)

  3. 为什么在这里已经明确指定了可选。

  4. 第二行文档中的修改是什么意思




如果底层集合被修改,则不指定迭代器的行为



解决方案

#1 :可选意味着您可以实现抛出 UnsupportedOperationException



#2:This操作是可选的,因为有时你不希望修改迭代器的内容。或者操作的鲁棒性理解什么?



编辑#4:迭代器的行为是未指定的如果基础集合被修改



通常,您使用迭代器执行

 列表与LT;字符串> 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();
...
}

如果你现在想删除一个项目



  c.remove(Item 2) ; 

这是不干净,可能破坏数据在您的列表/集合/ ...中,应该避免。而是通过迭代器

remove()item

  i.remove(); 


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()

Removes 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();

这篇关于为什么iterator.remove()被描述为可选操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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