在迭代期间向集合添加元素 [英] Adding elements to a collection during iteration

查看:37
本文介绍了在迭代期间向集合添加元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在迭代时向集合添加元素?

Is it possible to add elements to a collection while iterating over it?

更具体地说,我想迭代一个集合,如果一个元素满足某个条件,我想向集合中添加一些其他元素,并确保这些添加的元素也被迭代.(我意识到这可能导致无限循环,但我很确定它不会在我的情况下.)

More specifically, I would like to iterate over a collection, and if an element satisfies a certain condition I want to add some other elements to the collection, and make sure that these added elements are iterated over as well. (I realise that this could lead to an unterminating loop, but I'm pretty sure it won't in my case.)

来自 Sun 的 Java 教程表明这是不可能:请注意,Iterator.remove 是在迭代期间修改集合的唯一安全方式;如果底层集合以任何其他方式修改,则行为未指定,而迭代正在进行中."

The Java Tutorial from Sun suggests this is not possible: "Note that 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."

所以如果我不能用迭代器做我想做的事,你建议我做什么?

So if I can't do what I want to do using iterators, what do you suggest I do?

推荐答案

如何使用要迭代的元素构建一个队列;当你想添加元素时,将它们排在队列的末尾,并不断删除元素,直到队列为空.这就是广度优先搜索通常的工作方式.

How about building a Queue with the elements you want to iterate over; when you want to add elements, enqueue them at the end of the queue, and keep removing elements until the queue is empty. This is how a breadth-first search usually works.

这篇关于在迭代期间向集合添加元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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