如何迭代和修改 Java 集?

2022-01-17 00:00:00 set java

假设我有一个整数集,我想递增集合中的每个整数.我该怎么做?

Let's say I have a Set of Integers, and I want to increment every Integer in the Set. How would I do this?

我是否可以在迭代时添加和删除集合中的元素?

Am I allowed to add and remove elements from the set while iterating it?

我是否需要创建一个新集合,以便在迭代原始集合时将元素复制并修改"到其中?

Would I need to create a new set that I would "copy and modify" the elements into, while I'm iterating the original set?

如果集合的元素是不可变的怎么办?

What if the elements of the set are immutable?

推荐答案

您可以在迭代期间使用 Iterator 对象安全地从集合中移除;尝试在迭代时通过其 API 修改集合将破坏迭代器.Set 类通过 getIterator() 提供了一个迭代器.

You can safely remove from a set during iteration with an Iterator object; attempting to modify a set through its API while iterating will break the iterator. the Set class provides an iterator through getIterator().

然而,Integer 对象是不可变的;我的策略是遍历集合,对于每个整数 i,将 i+1 添加到一些新的临时集合中.完成迭代后,从原始集合中移除所有元素并添加新临时集合的所有元素.

however, Integer objects are immutable; my strategy would be to iterate through the set and for each Integer i, add i+1 to some new temporary set. When you are finished iterating, remove all the elements from the original set and add all the elements of the new temporary set.

Set<Integer> s; //contains your Integers
...
Set<Integer> temp = new Set<Integer>();
for(Integer i : s)
    temp.add(i+1);
s.clear();
s.addAll(temp);

相关文章