Collection - Iterator.remove()vs Collection.remove() [英] Collection - Iterator.remove() vs Collection.remove()
问题描述
根据Sun,
Iterator.remove是在
迭代期间修改集合的唯一安全方法;如果在迭代进行过程中以任何其他方式修改基础集合
,则行为未指定。
"Iterator.remove is the only safe way to modify a collection during iteration; the behavior is unspecified if the underlying collection is modified in any other way while the iteration is in progress."
我有两个问题:
- 是什么让这个操作Iterator.remove()比其他操作稳定?
- 为什么它们提供了Collection.remove()方法,如果它在大多数用例中没用?
推荐答案
如果你正在迭代一个集合并使用:
If you're iterating over a collection and use:
Collection.remove()
您可以获得运行时错误(特别是ConcurrentModifcationException),因为您正在更改对象的状态之前用于构造完成循环所必需的显式调用系列。
you can get runtime errors (specifically ConcurrentModifcationException) because you're changing the state of the object used previously to construct the explicit series of calls necessary to complete the loop.
如果你使用:
Iterator.remove()
您告诉运行时您想要更改基础集合并重新评估必要的显式系列调用完成循环。
you tell the runtime that you would like to change the underlying collection AND re-evaluate the explicit series of calls necessary to complete the loop.
这篇关于Collection - Iterator.remove()vs Collection.remove()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!