Java:实现“重复直到没有变化”收藏
我正在尝试实现一种算法,该算法重复对集合(当前是列表)应用操作。在每个步骤中,可以在集合内添加、删除和更改元素(使用 getter 和 setter)。重复该算法,直到上一步中的集合没有发生任何更改。
元素的顺序不相关。但是,在下一个循环之前不应访问修改或创建的元素。
我的方法是有一个大的主循环和一个内部循环,该循环应用算法并将修改的、创建的和未更改的元素复制到第二个列表。内循环结束后,原始列表被清空并被新列表替换。如果新旧列表包含相同的元素,则主循环终止。
最好的方法是什么?是否有一个集合支持开箱即用?第3方也可以。
任何帮助将不胜感激!
I'm trying to implement an algorithm that repeatedly applies operations on a Collection (currently a List). In each step Elements can be added, removed and changed (using getters and setters) within the collection. The algorithm is repeated until no changes were made to the collection in the previous step.
The order of elements is not relevant. However a modified or created Element should not be accessed until the next loop.
My approach was to have a large mainloop, and an inner loop that applies the algorithm and copies modified, created and unchanged elements to a second List. After the inner loop finished, the original list is emptied and replaced by the new one. The main loop is terminated if the new and the old list contain the same elements.
What is the best way to do this? Is there a collection that supports this out of the box? 3rd party is also ok.
Any help would really be appreciated!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我只想使用一个在主循环开始时设置为 false 的布尔变量。当在内循环中对列表进行更改时,可以将其设置为 true,如果没有进行更改,则它保持为 false。如果这是真的,主循环可以继续循环,否则结束循环
I would just use a boolean variable that is set to false at the beginning of the main loop. When a change is made to the list in the inner loop this could be set to true, if no change is made it remains false. The main loop can then continue looping if this is true or finish looping otherwise
你的方法对我来说听起来很合理,但有很多收藏复制。我认为您可以将相同的集合输入到内部循环中,该循环会就地更新集合并指示是否进行了任何更改,例如 while (collectionUpdated)。
如果集合不是太大或者您不希望对其进行太多更改,则递归效果很好。
例如
Your approach sounds reasonable to me, but has lots of collection copying. I think you can feed the same collection into the inner loop that updates the collection in place and signals whether any changes were made, e.g. while (collectionUpdated).
If the collection is not too big or you don't expect many changes to it, recursion works well.
e.g.
既然您说顺序不相关,请使用
Set
接口,例如哈希集。您可以简单地使用equals
方法比较集合的相等性。Since you say that order is not relevant, use an implementation of the
Set
interface, for example HashSet. You can compare sets for equality simply with theequals
method.