Iterator.remove()是安全的,您可以这样使用它:
List<String> list = new ArrayList<>();// This is a clever way to create the iterator and call iterator.hasNext() like// you would do in a while-loop. It would be the same as doing:// Iterator<String> iterator = list.iterator();// while (iterator.hasNext()) {for (Iterator<String> iterator = list.iterator(); iterator.hasNext();) { String string = iterator.next(); if (string.isEmpty()) { // Remove the current element from the iterator and the list. iterator.remove(); }}注意,这
Iterator.remove()是在迭代过程中修改集合的唯一安全方法。如果在进行迭代时以任何其他方式修改了基础集合,则行为未指定。
来源:docs.oracle>收集接口
同样,如果您有个
ListIterator并想要添加项目,则可以使用
ListIterator#add,出于相同的原因I
terator#remove,它可以允许使用。
你的情况,你想从列表中删除,但同样的限制,如果想put成为一个
Map在迭代的内容。



